Attached to an array row that does not contain certain words… here is a solution to the problem.
Attached to an array row that does not contain certain words
I’m trying to create a list of rows that doesn’t contain 3 specific words.
word_list = ['Banned', 'On_Hold', 'Reviewing']
unknown_row = []
with open('UserFile.csv', newline='') as csvfile:
user_reader = csv.reader(csvfile, delimiter='\t')
for row in user_reader:
joined = ','.join(row)
for i in word_list:
if i in joined:
pass
else:
unknown_row.append(joined)
with open('unkown.csv', 'w', newline='') as output:
writer = csv.writer(output, delimiter=',')
writer.writerows(x.split(',') for x in unknown_row)
Here’s the thing, if only one word is included in the word_list, then it works. But if I include two or more words, not .
Any ideas?
Thanks
Solution
There is a problem with your code:
for i in word_list:
if i in joined:
pass
else:
unknown_row.append(joined)
Now, if a word in word_list
isn’t found in joined
, it continues to loop, so it still adds lines unless all find words from word_list
in that line (this won’t stop your code from dealing with the single “bad word” you come across). Conversely, if you find any word from word_list
in the line, you want to short-circuit the loop to break.
You can use any
:: here
if not any(i in joined for i in word_list):
unknown_row.append(joined)
That way, if a single word in word_list
is found in joined, the line is not added.