Friday, 15 February 2013

python - Returning lines containing two or more keywords -



python - Returning lines containing two or more keywords -

i want iterate through number of lines (containing text) , homecoming lines contain 2 or more of words in list of keywords.

i have been trying making wordlist , keywordlist sets utilize intersect function, like:

if len(set(line).intersection(set(keywords))) >1: print line

also tried various types of nested loops

if word in line

but no success yet.

you need utilize str.split , split line on whitespace before convert set:

if len(set(line.split()).intersection(set(keywords))) > 1:

see demonstration below:

>>> keywords = ['if', 'def', 'class'] >>> line = 'if def word' >>> len(set(line).intersection(set(keywords))) > 1 false >>> len(set(line.split()).intersection(set(keywords))) > 1 true >>>

without change, set of characters instead of set of words:

>>> line = 'if def word' >>> set(line) {' ', 'f', 'd', 'e', 'i', 'o', 'r', 'w'} >>> set(line.split()) {'word', 'if', 'def'} >>>

python set intersection

No comments:

Post a Comment