读取csv文件并将对象与列表进行比较(Reading csv file and compare objects to a list)

编程入门 行业动态 更新时间:2024-10-12 16:21:47
读取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 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 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 1

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

更多推荐

本文发布于:2023-08-05 14:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1435157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并将   对象   文件   列表   csv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!