开发者

Reading csv file and compare objects to a list

I have a .txt file,primary list, with strings like this:

f
r
y
h
g
j

and 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,j

My 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开发者_如何学JAVA 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)


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 1

Note: In Python 2.x, always open csv files in binary mode. In Python3.x, always open csv files with newline=''


The reading into primary_list adds \n to each number - you should remove it:

When appending to primary_list do:

for line in primary_data:
    primary_list.append(line.strip())

Note the strip call. Also, as you can see, you don't really need realines, since for line in primary_data already does what you need when primary_data is a file object.

Now, as a general comment, since you're using the primary list for lookup, I suggest replacing the list by a set - this will make things much faster if the list is large. Python sets are very efficient for key-based lookup, lists are not designed for that purpose.


Following code would solve the problem.

from __future__ import print_function
import csv
primary_data =  open('test_list.txt','r')

primary_list = [line.rstrip() for line in primary_data]

recipies_reader = csv.reader(open('recipies.csv','r'), delimiter =',')
for row in recipies_reader:
    count = 0
    for i in row:
       if i in primary_list:
           count += 1

    print (count)

Output

2
3
2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜