40

假设我正在解析一个文件,该文件;用作注释字符。我不想解析评论。因此,如果我的一行看起来像这样:

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'
4

8 回答 8

133

我建议说

line.split(";")[0]

这将为您提供所有字符的字符串,但不包括第一个“;” 特点。如果不 ”;” 字符存在,那么它会给你整行。

于 2009-07-24T15:18:42.370 回答
18

只需按注释对行进行拆分,然后获取第一个元素,例如

line.split(";")[0]
于 2009-07-24T15:18:36.757 回答
4

对于 Python 2.5 或更高版本,我将使用以下partition方法:

rtr = line.partition(';')[0].rstrip() + '\n'
于 2009-07-24T15:19:50.950 回答
4

因此,您需要在第一个分号处拆分行,取其之前的所有内容,去掉任何挥之不去的空白,并附加一个换行符。

rtr = line.split(";", 1)[0].rstrip() + '\n'

文档链接:

于 2009-07-24T17:46:50.377 回答
3
file = open(r'c:\temp\test.txt', 'r')
for line in file:   print
   line.split(";")[0].strip()
于 2009-07-24T15:27:49.843 回答
1

在一行 python 中使用换行符读取、拆分、剥离和连接行:

rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r'))
于 2009-07-24T15:46:47.787 回答
1

这是另一种方式:

在 [6] 中:line = "foo;bar"
在 [7] 中:line[:line.find(";")] + "\n"
出 [7]: 'foo\n'
于 2009-07-25T23:34:54.270 回答
-2

我没有用 python 测试过这个,但我在其他地方使用了类似的代码。

import re
content = open(r'c:\temp\test.txt', 'r').read()
content = re.sub(";.+", "\n")
于 2009-07-24T16:06:21.653 回答