过滤文本文件中包含特定单词的行 [英] Filter lines from a text file which contain a particular word

查看:110
本文介绍了过滤文本文件中包含特定单词的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,以过滤文本文件中包含苹果"一词的行,并将这些行写入新的文本文件.

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.

推荐答案

使用可以使用列表理解来获取所有包含"apple"的行:

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])

eyquem是对的:将其保留为迭代器并进行编写肯定更快

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)

这篇关于过滤文本文件中包含特定单词的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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