是否有更好/更简单的方法来过滤空白行? [英] Is there a better/simpler way to filter blank lines?

查看:77
本文介绍了是否有更好/更简单的方法来过滤空白行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一些文本文件,我想在

进程中删除空白行。有没有比我这里更简单的方法呢?


lines = filter(lambda line:len(line.strip())0,lines)


Thomas

I''m parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?

lines = filter(lambda line: len(line.strip()) 0, lines)

Thomas

推荐答案

tmallen:
tmallen:

我''解析一些文本文件,我想在

进程中删除空白行。有没有比我这里更简单的方法呢?

lines = filter(lambda line:len(line.strip())0,lines)
I''m parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?
lines = filter(lambda line: len(line.strip()) 0, lines)



xlines =(如果line.strip(),则行打开(文件名)行


再见,

bearophile

xlines = (line for line in open(filename) if line.strip())

Bye,
bearophile


成为********** **@lycos.com 写道:

tmallen:
tmallen:

> I'解析一些文本文件,我想在
过程中删除空白行。有没有比我这里更简单的方法呢?
lines = filter(lambda line:len(line.strip())0,lines)
>I''m parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?
lines = filter(lambda line: len(line.strip()) 0, lines)



xlines =(如果是line.strip(),则行打开(文件名)行


再见,

bearophile


xlines = (line for line in open(filename) if line.strip())

Bye,
bearophile



如果您想同时过滤/循环,或者如果您不想同时在内存中同时使用所有

行:


fp = open(filename,''r'')
$ f $ b for fp:

if line.strip( ):

继续




#做一些非空白的事情:



fp.close()


-Larry

Of if you want to filter/loop at the same time, or if you don''t want all the
lines in memory at the same time:

fp = open(filename, ''r'')
for line in fp:
if not line.strip():
continue

#
# Do something with the non-blank like:
#
fp.close()

-Larry


11月4日,4:30 * pm,bearophileH ... @ lycos.com写道:
On Nov 4, 4:30*pm, bearophileH...@lycos.com wrote:

tmallen:
tmallen:

我''解析一些文本文件,我想在

进程中删除空白行。有没有比我这里更简单的方法呢?

lines = filter(lambda line:len(line.strip())0,lines)
I''m parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?
lines = filter(lambda line: len(line.strip()) 0, lines)



xlines =(如果是line.strip(),则行打开(文件名)行


再见,

熊宝宝


xlines = (line for line in open(filename) if line.strip())

Bye,
bearophile



我必须遗漏一些东西:

I must be missing something:


>> xlines =(line for line(" new.data")如果line.strip())
xlines
>>xlines = (line for line in open("new.data") if line.strip())
xlines



< 0x6b648处的生成器对象>

<generator object at 0x6b648>


>> xlines.sort()
>>xlines.sort()



回溯(最近一次调用最后一次):

文件"< stdin>",第1行,< module>

AttributeError:''generator''对象没有属性''sort''


你怎么看?


Thomas

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ''generator'' object has no attribute ''sort''

What do you think?

Thomas


这篇关于是否有更好/更简单的方法来过滤空白行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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