【发布时间】:2017-09-26 10:37:29
【问题描述】:
我已经很多年没有使用过 Python 并试图重新使用它。我有一个 Input_file (.csv),我想对其进行解析并将输出存储在 output.csv 或 .txt 中
我已设法使用此代码解析 .csv 文件,并且在大多数情况下它可以工作,但我无法将其保存以保存到文件(问题 1)而不会出现以下错误(错误 1)
import csv
import re
import itertools
file_name = 'PhoneCallData1.txt'
try:
lol = list(csv.reader(open(file_name, 'r'), delimiter=' '))
count =0
except:
print('File cannot be opened:',file_name)
exit()
try:
fout = open('output.txt','w')
except:
Print("File cannot be written to:","OutputFile")
exit()
d = dict()
for item in itertools.chain(lol): # Lists all items (field) in the CSV file.
count +=1 # counter to keep track of row im looping through
if lol[count][3] is None:
print("value is not blank")
count +=1
else:
try:
check_date = re.search(r'(\d+/\d+/\d+)', lol[count][3]) # check to determine if date is a date
except:
continue
check_cost = re.compile(r'($+\d*)', lol[count][9]) # check to determine if value is a cost
if check_date ==TRUE:
try:
key =lol[count][3] # If is a date value, store key
except ValueError:
continue
if check_cost==TRUE:
value = lol[count][9] # if is a cost ($) store value
d[key] = value
print (d[key])
# fout.write((d[key])
# What if there is no value in the cell?
# I keep getting "IndexError: list index out of range", anyone know why?
# Is there a better way to do this?
# I only want to store the destination and the charge
现在是复杂的部分。我需要解析的文件在所需数据之前和之间有许多不相关的数据行。
数据格式
我想做什么; 我想遍历两列数据,只存储其中包含日期或成本的行,忽略其余数据。
import csv
import re
import itertools
lol = list(csv.reader(open('PhoneCallData1.txt', 'r'), delimiter=' '))
count =0
d = dict()
for item in itertools.chain(lol): #Lists all items (field) in the CSV file.
count +=1 # counter to keep track of row im looping through
check_date = re.search(r'(\d+/\d+/\d+)', lol[count][3]) #check to determine
check_cost = re.compile(r'($+\d*)', lol[count][9]) #check to determine if value is a cost
if check_date ==TRUE:
key =lol[count][3] #If is a date value, store key
if check_cost==TRUE:
value = lol[count][9] #if is a cost ($) store value
d[key] = value
print (d[key])
#What if there is no value in the cell?
# I keep getting "IndexError: list index out of range", anyone know why?
# Is there a better way to do this?
# I only want to store the destination and the charges
我尝试过的; 加载数据后,我尝试对其进行索引,但这似乎不起作用。 我创建它只是为了查看超过一定长度的行,但它的代码很糟糕。我希望有一些更实用和可重复使用的东西。
import re
with open('PhoneCallData1.txt','r') as f, open('sample_output.txt','w') as fnew:
for line in f:
if len(line) > 50:
print(line)
fnew.write(line + '\n')
Import csv
lol = list(csv.reader(open('PhoneCallData1.txt', 'rb'), delimiter='\t'))
#d = dict()
#key = lol[5][0] # cell A7
#value = lol[5][3] # cell D7
#d[key] = value # add the entry to the dictionary
不断出现索引越界错误
import re
import csv
match=re.search(r'(\d+/\d+/\d+)','testing date 11/12/2017')
print match.group(1)
尝试使用正则表达式在第一列数据中搜索日期。
注意:我想尝试 Pandas,但我觉得我需要从这里开始。任何帮助都会很棒。
【问题讨论】:
-
我的问题还没编译完,就意外提交了。
-
您的 for 循环似乎没有正确缩进。
-
缩进时出现“意外缩进”。
标签: python list csv for-loop itertools