2011-04-21 89 views
0

我觉得我过于简单化/ overcomplexify DOC有时解析,这里是我经常做的事:方法解析文档和规范行

data = open('data.txt', 'rb').read() 

for line in data.split('\n'): 
    if not line.strip(): 
     continue 

这:

import csv 

filenames=['first_name', 'last_name', 'email', 'postcode', 'telephone_no', ] 
reader = csv.DictReader(open('data.csv', 'rb'), filenames=filenames) 

for line in reader: 
    if line['email'].strip() 
     email = line['email'].strip() 
    if line['first_name'].strip() 
     first_name= line['first_name'].strip().capitalize() 
    if line['last_name'].strip() 
     last_name = line['last_name'].strip().capitalize() 
    if line['postcode'].strip() 
     postcode= line['postcode'].strip().upper().replace(' ','') 
    if line['telephone_no'].strip() 
     telephone_no = line['telephone_no'].strip() 

与此:

item = " 4 -2,5456+263 @5" 
item = ''.join([char for char in item if char.isdigit()]) 

item = "+34 0394-234553" 
item = item.replace('+','').replace(' ','').replace('-','') 

关于改进/替代方案的任何提示/建议? :)

+1

打开你的文件是这样的:'data = open(“data.txt”,“rb”)',然后这个'data line in data:'将遍历行。不需要'split()'。另外,请考虑使用'with'来确保文件已关闭。 – 2011-04-21 11:19:30

+0

谢谢@ Space_C0wb0y! – RadiantHex 2011-04-21 11:24:29

+2

@ Space_C0wb0y:你的意思可能是'对于数据行:' – eumiro 2011-04-21 11:26:12

回答

1
with open('data.txt', 'rb') as myfile: 
    for line in myfile: 
     if not line: 
      continue 

正如你可能想要做的东西线,可以进一步简化:

with open('data.txt', 'rb') as myfile: 
    for line in myfile: 
     if line: 
      do_whateveryouwant(line) 
2

你可以使非空行列表中的一个班轮

lines = filter(None, (line.strip() for line in open('data.txt', 'rb').readlines())) 

最快的方法,以消除一切,除了某些字符

使用__contains__字符串常量的方法filterfilter如果与字符串一起使用,则返回字符串)。所以你可以这样删除非数字字符:

import string 
filter(string.digits.__contains__, " 4 -2,5456+263 @5") 
+0

@lmran:太棒了!我真的很喜欢__contains__的例子,谢谢分享:) – RadiantHex 2011-04-21 12:04:54

+1

从'Python中的文本处理'发现了这个http://gnosis.cx/TPiP/ – Imran 2011-04-21 12:20:11