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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16432203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:36:23  来源:igfitidea点击:

How to check in Python if string is in a text file and print the line?

pythonstringtextsyntax

提问by bn60

What I am trying to do is to check whether this string is found in the text file. If it does, I want it to printout that line, else printout a message.

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

I have implemented this code so far:

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

 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!')

I've tried implementing that but I got a syntax error.

我试过实现它,但出现语法错误。

It says:

它说:

invalid syntax at the line -- for w.readlines():

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

Any idea on how to go with this line of code?

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

采纳答案by Ashwini Chaudhary

You should try something like this:

你应该尝试这样的事情:

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

If you are searching for exact words instead of just sub-string then I would suggest using regexhere.

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

Example:

例子:

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

回答by kenorb

Here is a bit simpler example by using inoperator:

这是一个使用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!')

If you'd like to know the position of the string, then you can use find()instead of inoperator.

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