读取csv文件并将对象与列表进行比较(Reading csv file and compare objects to a list)
我有一个.txt文件,主列表,字符串如下:
f r y h g j我有一个.csv文件,食谱列表,有这样的行:
d,g,r,e,w,s j,f,o,b,x,q,h y,n,b,w,q,j我的程序会抛出每一行并计算属于主列表的对象数量,例如在这种情况下结果是:2 3 2我总是得到0,错误必须是愚蠢的,但我无法弄清楚:
from __future__ import print_function import csv primary_data = open('test_list.txt','r') primary_list = [] for line in primary_data.readlines(): line.strip('\n') primary_list.append(line) recipes_reader = csv.reader(open('test.csv','r'), delimiter =',') for row in recipes_reader: primary_count = 0 for i in row: if i in primary_list: primary_count += 1 print (primary_count)I have a .txt file,primary list, with strings like this:
f r y h g jand I have a .csv file,recipes list, with rows like this:
d,g,r,e,w,s j,f,o,b,x,q,h y,n,b,w,q,jMy programe is going throw each row and counts number of objects which belongs to primary list, for example in this case outcome is: 2 3 2 I always get 0, the mistake must be silly, but I can't figure it out:
from __future__ import print_function import csv primary_data = open('test_list.txt','r') primary_list = [] for line in primary_data.readlines(): line.strip('\n') primary_list.append(line) recipes_reader = csv.reader(open('test.csv','r'), delimiter =',') for row in recipes_reader: primary_count = 0 for i in row: if i in primary_list: primary_count += 1 print (primary_count)最满意答案
这是踩踏金属版的基本款:
from __future__ import print_function import csv with open('test_list.txt', 'r') as f: # with statement ensures your file is closed primary_set = set(line.strip() for line in f) with open('test.csv', 'rb') as f: #### see note below ### for row in csv.reader(f): # delimiter=',' is the default print(sum(i in primary_set for i in row)) # i in primary_set has int value 0 or 1注意:在Python 2.x中,始终以二进制模式打开csv文件。 在Python3.x中,始终使用newline=''打开csv文件
Here's the bare-essentials pedal-to-the-metal version:
from __future__ import print_function import csv with open('test_list.txt', 'r') as f: # with statement ensures your file is closed primary_set = set(line.strip() for line in f) with open('test.csv', 'rb') as f: #### see note below ### for row in csv.reader(f): # delimiter=',' is the default print(sum(i in primary_set for i in row)) # i in primary_set has int value 0 or 1Note: In Python 2.x, always open csv files in binary mode. In Python3.x, always open csv files with newline=''
更多推荐
发布评论