我正在尝试编写一个读取文件内容的程序,逐行搜索文件,当某些字符串出现时,它会将该行返回到我的屏幕。
我成功的时候,它只是我要找的一个字符串。我现在正在尝试的是,当我告诉Python寻找一些字符串时,当其中一个字符串出现在文件中时,它会打印出该行
import urllib2
file = urllib2.urlopen("http://helloworldbook2.com/data/message.txt")
message = file.read()
#print message
# Saves the content of the URL in a file
temp_output = open("tempfile.txt", "w")
temp_output.write(message)
temp_output.close()
# Displays the line where a certain word occurs
wordline = [line for line in message.split('\n') if ("enjoying" or "internet") in line]
line = wordline[0]
print line
所以我的问题是("享受"或"互联网")部分。
谢谢!
答案 0 :(得分:0)
这种语法不好:
if ("enjoying" or "internet")
相反,您可以使用any
或all
:
words = ["enjoying", "internet"]
if all(x in line for x in words)