如果字符串在文本文件中并打印行,如何检查Python?

bn6*_*n60 5 python string syntax text

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

到目前为止,我已实现此代码:

 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!')
Run Code Online (Sandbox Code Playgroud)

我已经尝试过实现,但是我遇到了语法错误.

它说:

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

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

Ash*_*ary 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
Run Code Online (Sandbox Code Playgroud)

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

例:

>>> import re
>>> strs = "foo bar spamm"
>>> "spam" in strs        
True
>>> bool(re.search("\b{0}\b".format("spam"),strs))
False
Run Code Online (Sandbox Code Playgroud)