我有一个列表“a”,我需要用文本文件“hello.txt”的行打印列表中所有匹配的字母。但它只打印列表和行中的第一个单词而不是所有列表和行
a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
for key in a:
for line in f:
if key in line:
print line, key
结果为:
comp and python
comp
期望的输出:
comp and python
comp
graphics and pixel
graphics
micro sd card
card
python part
part
请帮助我获得欲望输出。答案将不胜感激!
最佳答案
文件对象 f
是一个迭代器。 Once you've iterated it, it's exhausted ,因此您的 for line in f:
循环将仅适用于第一个键。将行存储在 list
中,然后它应该可以工作。
a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
lines = f.readlines() # loop the file once and store contents in list
for key in a:
for line in lines:
if key in line:
print line, key
或者,您也可以交换循环,这样您只迭代文件一次。如果文件真的很大,这可能会更好,因为您不必一次将所有内容加载到内存中。当然,这样您的输出可能会略有不同(顺序不同)。
a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
for line in f: # now the file is only done once...
for key in a: # ... and the key loop is done multiple times
if key in line:
print line, key
或者,正如 Lukas 在评论中所建议的那样,使用原始循环并通过在外部 key 的每次迭代中调用
循环。f.seek(0)
来“重置”文件迭代器
关于python parse 仅打印列表中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24849562/