如果字符串在文本文件中,如何检查 Python 并打印该行? [英] How to check in Python if string is in a text file and print the line?
问题描述
我要做的是检查是否在文本文件中找到了这个字符串.如果是这样,我希望它打印出该行,否则打印出一条消息.
到目前为止我已经实现了这段代码:
def check_string(string):w = raw_input("请输入英文单词:")如果 w 在 open('example.txt').read():对于 w.readlines():印刷线别的:print('找不到翻译!')
我已经尝试过实现,但出现语法错误.
它说:
<块引用>该行的语法无效——对于 w.readlines():
知道如何使用这行代码吗?
你应该尝试这样的事情:
导入重新def check_string():#如果您不使用它们,则无需将参数传递给函数w = raw_input("请输入英文单词:")#使用`with`上下文管理器打开文件,它会自动为你关闭文件with open("example.txt") as f:发现 = 错误for line in f: #iterate over the file at a time (memory高效)if re.search("\b{0}\b".format(w),line): #如果找到的字符串在当前行,则打印它印刷线发现 = 真如果没有找到:print('找不到翻译!')check_string() #现在调用函数
如果您要搜索确切的单词而不仅仅是子字符串,那么我建议在此处使用 regex
.
示例:
<预><代码>>>>进口重新>>>strs = "foo bar spamm">>>strs中的垃圾邮件"真的>>>bool(re.search("\b{0}\b".format("spam"),strs))错误的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():
Any idea on how to go with this line of code?
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 regex
here.
Example:
>>> import re
>>> strs = "foo bar spamm"
>>> "spam" in strs
True
>>> bool(re.search("\b{0}\b".format("spam"),strs))
False
这篇关于如果字符串在文本文件中,如何检查 Python 并打印该行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!