[英]How to check in Python if string is in a text file and print the line?
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? 关于如何使用这行代码的任何想法?
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. 如果您正在搜索确切的单词而不仅仅是子字符串,那么我建议在这里使用
regex
。
Example: 例:
>>> import re
>>> strs = "foo bar spamm"
>>> "spam" in strs
True
>>> bool(re.search("\b{0}\b".format("spam"),strs))
False
Here is a bit simpler example by using in
operator: 通过
in
运算符中使用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 in
operator. 如果您想知道字符串的位置,那么您可以使用
find()
而不是in
运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.