[英]In Python 2.4, how can I strip out characters after ';'?
假设我正在解析一个使用;
作为注释字符。 我不想解析评论。 因此,如果我一行看起来像这样:
example.com. 600 IN MX 8 s1b9.example.net ; hello!
除此以外,是否有更简单/更优雅的方法来去除字符:
rtr = ''
for line in file:
trig = False
for char in line:
if not trig and char != ';':
rtr += char
else:
trig = True
if rtr[max(rtr)] != '\n':
rtr += '\n'
我建议说
line.split(";")[0]
这将为您提供所有字符的字符串,直到但不包括第一个“;” 字符。 如果不 ”;” 字符存在,那么它将给您整行。
只是通过注释在行上拆分,然后获取第一个元素,例如
line.split(";")[0]
对于Python 2.5或更高版本,我将使用partition
方法:
rtr = line.partition(';')[0].rstrip() + '\n'
file = open(r'c:\temp\test.txt', 'r')
for line in file: print
line.split(";")[0].strip()
使用python的一行来读取,拆分,剥离和使用newline合并行:
rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r'))
这是另一种方式:
In [6]: line = "foo;bar" In [7]: line[:line.find(";")] + "\n" Out[7]: 'foo\n'
我没有用python测试过,但是在其他地方使用了类似的代码。
import re
content = open(r'c:\temp\test.txt', 'r').read()
content = re.sub(";.+", "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.