Python 打印文件中单词出现的行
我试图编写一个程序,读取文件内容,逐行搜索文件,当出现某些字符串时,它会将该行返回到屏幕 我已经成功了,当它只是一个字符串,我正在寻找。我现在尝试的是,当我告诉Python查找大量字符串时,当其中一个字符串出现在文件中时,它会打印这一行Python 打印文件中单词出现的行,python,python-2.7,Python,Python 2.7,我试图编写一个程序,读取文件内容,逐行搜索文件,当出现某些字符串时,它会将该行返回到屏幕 我已经成功了,当它只是一个字符串,我正在寻找。我现在尝试的是,当我告诉Python查找大量字符串时,当其中一个字符串出现在文件中时,它会打印这一行 import urllib2 file = urllib2.urlopen("http://helloworldbook2.com/data/message.txt") message = file.read() #print message # Saves
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
所以我的问题是(“享受”或“互联网”)部分
谢谢 这种语法不好:
if ("enjoying" or "internet")
相反,您可以使用any
或all
:
words = ["enjoying", "internet"]
if all(x in line for x in words)
可能有你想要的解决方案。是的,这确实解决了我的问题!谢谢