Question

I have a list of words in a list self.terms, and a string line. If any of the terms in the list are in line, I'd like to write them out to a file terms_file.

I used any() as shown below, but this returns a boolean.

any(terms_file.write(term) for term in self.terms if term in line)

How can I write out to the file? I tried adding a lambda but I'm not really familiar with them and that did not work. I got some syntax errors, but after some changes, I got False returned again.

Is it possible to do this using any()?

Was it helpful?

Solution

Don't use any() here; you don't even use the return value.

To write all matching terms, use:

terms_file.write(''.join(term for term in self.terms if term in line))

but it'd be better to just use a regular loop; readability counts!

for term in self.terms:
    if term in line:
        terms_file.write(term)

Use any() only if you want to know about the boolean result of the test; any() stops iterating when it finds the first True value. In your case terms_file.write() returns None, so it'll never even encounter True and always return False.

OTHER TIPS

any will tell you whether any of the terms where present in line (hence the name).

You can just create a list of those terms:

present_terms = list(terms_file.write(term) for term in self.terms if term in line)

and write that to a file, possibly after joining the list items:

out_file.write(' '.join(present_terms))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top