6

我要做的是检查是否在文本文件中找到了这个字符串。如果是这样,我希望它打印出该行,否则打印出一条消息。

到目前为止,我已经实现了这段代码:

 def check_string(string):

     w = raw_input("Input the English word: ")
        if w in open('example.txt').read():
            for w.readlines():
                print line
        else:
            print('The translation cannot be found!')

我已经尝试实现它,但出现语法错误。

它说:

该行的语法无效——对于 w.readlines():

关于如何使用这行代码的任何想法?

4

2 回答 2

8

你应该尝试这样的事情:

import re
def check_string():
    #no need to pass arguments to function if you're not using them
    w = raw_input("Input the English word: ")

    #open the file using `with` context manager, it'll automatically close the file for you
    with open("example.txt") as f:
        found = False
        for line in f:  #iterate over the file one line at a time(memory efficient)
            if re.search("\b{0}\b".format(w),line):    #if string found is in current line then print it
                print line
                found = True
        if not found:
            print('The translation cannot be found!')

check_string() #now call the function

如果您正在搜索确切的单词而不仅仅是子字符串,那么我建议您regex在此处使用。

例子:

>>> import re
>>> strs = "foo bar spamm"
>>> "spam" in strs        
True
>>> bool(re.search("\b{0}\b".format("spam"),strs))
False
于 2013-05-08T03:34:34.387 回答
4

这是使用in运算符的一个更简单的示例:

w = raw_input("Input the English word: ") # For Python 3: use input() instead
with open('foo.txt') as f:
    found = False
    for line in f:
        if w in line: # Key line: check if `w` is in the line.
            print(line)
            found = True
    if not found:
        print('The translation cannot be found!')

如果您想知道字符串的位置,那么您可以使用find()代替in运算符。

于 2015-06-01T19:08:33.703 回答