[英]Comparing two lists of strings .CSV
I'm trying to write a script to compare two lists of strings from different spreadsheets and to print off a list of strings common to both spreadsheets. 我正在尝试编写一个脚本来比较来自不同电子表格的两个字符串列表,并打印两个电子表格共有的字符串列表。 I'm a total novice, but so far I've got:
我是一个新手,但到目前为止,我有:
import csv
f1 = file("KaySinTan09.csv", "r")
f2 = file("Khanna11.csv", "r")
c1=csv.reader(open('KaySinTan09.csv', 'rb'), delimiter=' ', quotechar='|')
c2=csv.reader(open('Khanna11.csv', 'rb'), delimiter=' ', quotechar='|')
output = c1.intersection(c2)
print output
I get an error saying "AttributeError: '_csv.reader' object has no attribute 'intersection'". 我得到一个错误,说“AttributeError:'_ csv.reader'对象没有属性'交集'”。
Any advice on where I'm going wrong? 关于我哪里出错的任何建议?
csv.reader is not a set, you need to convert it to one in order to do this: csv.reader不是一个集合,您需要将其转换为一个才能执行此操作:
c1= set(csv.reader(open('KaySinTan09.csv', 'rb'), delimiter=' ', quotechar='|'))
c2 = set(csv.reader(open('Khanna11.csv', 'rb'), delimiter=' ', quotechar='|'))
output = c1.intersection(c2)
print output
csv.reader
does not return a list - it returns a CSV reader object - so the .intersection
method will not work. csv.reader
不返回列表 - 它返回CSV读取器对象 - 因此.intersection
方法不起作用。 Maybe this will: 也许这会:
c1=csv.reader(open('KaySinTan09.csv', 'rb'), delimiter=' ', quotechar='|')
c2=csv.reader(open('Khanna11.csv', 'rb'), delimiter=' ', quotechar='|')
c1_list = []
c2_list = []
for c in c1:
c1_list.append(c)
for c in c2:
c2_list.append(c)
output = set(c1_list).intersection(set(c2_list))
print output
This is not tested. 这没有经过测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.