Ash*_*ton 1 python regex list-comprehension
我正在尝试使用类似于以下代码的列表解析来拆分文件:
lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)]
Run Code Online (Sandbox Code Playgroud)
但是,行列表始终具有空字符串作为最后一个元素.有没有人知道避免这种情况的方法(不包括后来放一个pop()的淤泥)?
把正则表达式锤子拿走:-)
readlines()这几天几乎已经过时了.str.strip()(和它的朋友,lstrip()和rstrip()).file用作变量名.这file是一个糟糕的形式,因为它是一个内置的功能.您可以将代码编写为:
lines = []
f = open(filename)
for line in f:
if not line.startswith('com'):
lines.append(line.strip())
Run Code Online (Sandbox Code Playgroud)
如果你仍然在那里得到空行,你可以添加一个测试:
lines = []
f = open(filename)
for line in f:
if line.strip() and not line.startswith('com'):
lines.append(line.strip())
Run Code Online (Sandbox Code Playgroud)
如果你真的想要它在一行:
lines = [line.strip() for line in open(filename) if line.strip() and not line.startswith('com')]
Run Code Online (Sandbox Code Playgroud)
最后,如果您使用的是python 2.6,请查看with语句以进一步改进.
| 归档时间: |
|
| 查看次数: |
11498 次 |
| 最近记录: |