[英]Python: Using CSV to parse(?) variables and then output that to another file
[英]Parse delimited csv file using Python, output to terminal or file
我一直在研究Python脚本来解析csv文件中的单个定界列。 但是,该列有多个不同的定界符,我不知道该怎么做。
我还有另一个适用于类似数据的脚本,但无法使该脚本正常工作。 下面的数据在该行的单个列中。 我想让脚本将其解析出来,并在每个之间添加标签。 然后,我想将此数据附加到仅包含唯一项的列表中。 通常,我正在处理此数据的几百行,并且想解析整个文件,然后仅在两列中返回唯一项(一个用于IP,另一个用于URL)。
要解析的数据:123.123.123.123::url.com,url2.com,234.234.234.234::url3.com(注意“:”和“,”用作同一行上的分隔符)
我正在使用的脚本:
import sys
import csv
csv_file = csv.DictReader(open(sys.argv[1], 'rb'), delimiter=':')
uniq_rows = []
for column in csv_file:
X = column[' IP'].split(':')[-1]
row = X + '\t'
if row not in uniq_rows:
uniq_rows.append(row)
for row in uniq_rows:
print row
有人知道我该怎么做吗?
将列表( uniq_rows = []
)更改为一个集合( uniq_rows = set()
):
csv_file = csv.DictReader(open(sys.argv[1], 'rU'), delimiter=':')
uniq_rows = set()
for column in csv_file:
X = column[' IP'].split(':')[-1]
row = X + '\t'
uniq_rows.add(row)
for row in list(uniq_rows):
print row
如果您需要进一步的帮助,请发表评论
您也可以只使用replace来更改您的导入行:(我猜不是过度的pythonic,而是标准内置的):
>>> a = "123.123.123.123::url.com,url2.com,234.234.234.234::url3.com"
>>> a = a.replace(',','\t')
>>> a = a.replace(':','\t')
>>> print (a)
123.123.123.123 url.com url2.com 234.234.234.234 url3.com
>>>
如此处评论中所述,通过简单的文本操作即可(希望)在清除非重复项之前获得正确的输出:
import sys
read_raw_file = open('D:filename.csv') # open current file
read_raw_text = read_raw_file.read()
new_text = read_raw_text.strip()
new_text = new_text.replace(',','\t')
# new_text = new_text.replace('::','\t') optional if you want double : to only include one column
new_text = new_text.replace(':','\t')
text_list = new_text.split('\n')
unique_items = []
for row in text_list:
if row not in unique_items:
unique_items.append(row)
new_file ='D:newfile.csv'
with open(new_file,'w') as write_output_file: #generate new file
for i in range(0,len(unique_items)):
write_output_file.write(unique_items[i]+'\n')
write_output_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.