Can only repeat only through csv reader

So, I basically have an extremely long list of strings and a CSV file containing a column of strings and a column of numbers. I need to scroll through an extremely long list of lines, and for each of them skip the lines of the CSV file, checking each line in the first column of the CSV, to see if it appears in my line, and if so, add a number in another column to something . A minimal example might be

import csv sList = ['a cat', 'great wall', 'mediocre wall'] vals = [] with open('file.csv', 'r') as f: r = csv.reader(f) for w in sList: val = 0 for row in r: if row[0] in w: val += 1 vals.append(val) 

An example CSV file with which I could use it might be

 a, 1 great, 2 

Of course, csv.reader (f) creates an iterability that I can only skip once. I saw recommendations in other places to use itertools, but all the recommendations that I found were related to problems that involved cycling through a CSV file several times, usually twice. If I tried to use this to cycle through CSV many times, I’m not sure what this would mean for memory consumption, and in general I’m just interested to know about the smartest way to approach this problem.

+5
source share
1 answer

You need to "reset" the file iterator:

 import csv sList = ['a cat', 'great wall', 'mediocre wall'] vals = [] with open('data.csv', 'r') as f: r = csv.reader(f) for w in sList: val = 0 f.seek(0) #<-- set the iterator to beginning of the input file for row in r: print(row) if row[0] in w: val += 1 vals.append(val) 
+7
source

Source: https://habr.com/ru/post/1208554/


All Articles