Filter lines from a text file which contain a particular word

こ雲淡風輕ζ 提交于 2019-12-17 22:37:41

问题


I want to write a program which filters the lines from my text file which contain the word "apple" and write those lines into a new text file.

What I have tried just writes the word "apple" in my new text file, whereas I want whole lines.


回答1:


Use can get all lines containing 'apple' using a list-comprehension:

[ line for line in open('textfile') if 'apple' in line]

So - also in one code-line - you can create the new textfile:

open('newfile','w').writelines([ line for line in open('textfile') if 'apple' in line])

And eyquem is right: it's definitely faster to keep it as an iterator and write

open('newfile','w').writelines(line for line in open('textfile') if 'apple' in line)



回答2:


from itertools import ifilter

with open('source.txt','rb') as f,open('new.txt','wb') as g:

    g.writelines( ifilter(lambda line: 'apple' in line, f))



回答3:


Using generators, this is memory efficient and fast

def apple_finder(file):
    for line in file:
        if 'apple' in line:
             yield line


source = open('forest','rb')

apples = apple_finder(source)

I love easy solutions with no brain damage for reading :-)




回答4:


if "apple" in line: should work.




回答5:


For Python3 - here is working and fast example

with open('input.txt', 'rb') as file_in:
    with open("output.txt", "wb") as file_out:
        file_out.writelines(filter(lambda line: b'lines with this text' in line, file_in))


来源:https://stackoverflow.com/questions/5245058/filter-lines-from-a-text-file-which-contain-a-particular-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!