python parse只打印列表的第一行 [英] python parse prints only first line from list

查看:560
本文介绍了python parse只打印列表的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表'a',在这里我需要打印文本文件'hello.txt'的行中所有匹配的字母,但是它只打印列表和行中的第一个单词而不是所有列表和行

I have a list 'a',where I need to print all the matching letters of the list with the line of a text file 'hello.txt'.But it only prints the first word from the list and line instead of all the list and lines

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

请帮助我获得期望的输出.答案将不胜感激!

Please help me to get desires output.Answers willbe appreciated!

推荐答案

文件对象f是迭代器. 一旦您对其进行了迭代,就筋疲力尽了,因此您的for line in f:循环仅适用于第一个键.将这些行存储在list中,然后它应该可以工作.

The file-object f is an iterator. Once you've iterated it, it's exhausted, thus your for line in f: loop will only work for the first key. Store the lines in a list, then it should work.

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

或者,您也可以交换循环,因此只将文件迭代一次.如果文件很大,这可能会更好,因为您不必一次将所有内容加载到内存中.当然,通过这种方式,您的输出可能会略有不同(以不同的顺序).

Alternatively, you could also swap the loops, so you iterate the file only once. This could be better if the file is really big, as you won't have to load all it's contents into memory at once. Of course, this way your output could be slights different (in a different order).

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)来重置"文件迭代器.

Or, as suggested by Lukas in the comments, use your original loop and 'reset' the file-iterator by calling f.seek(0) in each iteration of the outer key loop.

这篇关于python parse只打印列表的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆