2009-07-24 63 views
25

假设我正在解析文件,该文件使用;作为注释字符。我不想解析评论。所以,如果我的线路是这样的:在Python 2.4中,如何在';'之后去掉字符?

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' 
+0

你使用python <2.5吗? – SilentGhost 2009-07-24 18:34:18

+0

是的,python2.4。应该提到的是在?? – lfaraone 2009-07-24 19:42:45

+3

well python2.4是当前稳定版本之后的**两个**版本。你怎么看? – SilentGhost 2009-07-24 19:47:13

回答

85

我建议说

line.split(";")[0] 

这将给你一个字符串的所有字符,但不包括第一个“;”字符。如果不 ”;”字符存在,那么它会给你整条线。

+14

+1你可以使用1来表示maxsplit param是完美的 – Jiri 2009-07-24 15:26:39

12

只是做就行了分裂的评论则得到的第一个元素 如

line.split(";")[0] 
4

对于Python 2.5或更大,我会使用partition方法:

rtr = line.partition(';')[0].rstrip() + '\n' 
+0

不适用于版本<2.5 ++ – ghostdog74 2009-07-24 15:21:07

+2

@ ghostdog74:python的稳定版本是2.6和3.1 – SilentGhost 2009-07-24 15:29:53

2
file = open(r'c:\temp\test.txt', 'r') 
for line in file: print 
    line.split(";")[0].strip() 
1

阅读,分裂,剥离,并加入新行线的所有在python的一行:

rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r')) 
-2

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

import re 
content = open(r'c:\temp\test.txt', 'r').read() 
content = re.sub(";.+", "\n") 
2

所以你要分割的第一个分号行,之前采取的一切,去掉所有挥之不去的空白,并追加一个换行符。

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

文档链接:

0

这里是另一种方式:

 
In [6]: line = "foo;bar" 
In [7]: line[:line.find(";")] + "\n" 
Out[7]: 'foo\n'