So I have a list of key words and I'm trying to check if any of those words are found in a line in my csv sheet, if present, it should be marked. The code I have works perfectly except when the line has more than one of those keywords, it won't be marked. Thoughts?
import sys
import csv
nk = ('aaa','bbb','ccc')
with open(sys.argv[1], "rb") as f:
reader = csv.reader(f, delimiter = '\t')
for row in reader:
string=str(row)
if any(word in string for word in nk):
row.append('***')
print '\t'.join(row)
else:
print '\t'.join(row)
Thanks in advance!
Use set intersection to get all the common words:
nk = {'aaa','bbb','ccc'}
seen = set() #keep as track of items seen so far in this set
with open(sys.argv[1], "rb") as f:
...
for row in reader:
#update `seen` with the items found common between `nk` and the current `row`
seen.update(nk.intersection(row))
...
Don't convert row
to a string( string=str(row)
), in
operator works fine with lists as well and behaves differently than string's in
:
>>> strs = "['foo','abarc']"
>>> 'bar' in strs #substring search
True
>>> lis = ['foo','abarc'] #item search
>>> 'bar' in lis
False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.