我正在尝试在字符串上出现单词时打印,但实际上它不会打印任何内容。我的文本文件是:
words={'apple', 'banana', 'pie'}
strings={'Hello World!', 'I love pie', 'Ate an apple'}
with open("words.txt") as words_file:
with open("strings.txt") as strings_file:
all_strings = list(map(str.strip,strings_file))
for a_string in all_strings:
for word in words_file:
if word in a_string:
print a_string
,输出就像
吃了一个苹果
我爱馅饼
答案 0 :(得分:0)
from itertools import izip
with open("file1.txt") as f1:
with open("file2.txt") as f2:
for f1_line,f2_line in izip(f1,f2): #this will return the same lines from both files
do_something(f1_line,f2_line)
你一遍又一遍地看到同样的事情的原因是你
for line2 in file2:
print line1.split() # line 1 will not change until you go through every line in file2
[edit]如评论中所述,如果你使用的是python2.7 +,你可以将文件开放合并为一行
with open("file1.txt") as f1, open("file2.txt") as f2:
for f1_line,f2_line in izip(f1,f2): #this will return the same lines from both files
do_something(f1_line,f2_line)
下面的代码可以做你想要的......
from itertools import izip
with open("words.txt") as words_file:
with open("strings.txt") as strings_file:
all_strings = list(map(str.strip,strings_file))
for word in words_file:
for a_string in all_strings:
if word in a_string:
print a_string