我觉得我过于简单化/ 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('-','')
关于改进/替代方案的任何提示/建议? :)
打开你的文件是这样的:'data = open(“data.txt”,“rb”)',然后这个'data line in data:'将遍历行。不需要'split()'。另外,请考虑使用'with'来确保文件已关闭。 – 2011-04-21 11:19:30
谢谢@ Space_C0wb0y! – RadiantHex 2011-04-21 11:24:29
@ Space_C0wb0y:你的意思可能是'对于数据行:' – eumiro 2011-04-21 11:26:12