Python: translating/replacing in a string words that aren't the ones you want
Basically, I've got a bunch of phrases and I'm only 开发者_StackOverflowinterested in the ones that contain certain words. What I want to do is 1) find out if that word is there and if it is, 2) erase all the other words. I could do this with a bunch of if's and for's but I was wondering if there'd be a short/pythonic approach to it.
A suggested algorithm:
- For each phrase
- Find whether the interesting word is there
- If it is, erase all other words
- Otherwise, just continue to the next phrase
Yes, implementing this would take "a bunch of ifs and fors", but you would be surprised how easily and cleanly such logic translates to Python.
A more succinct way to achieve the same would be to use a list comprehension, which flattens this logic somewhat. Given that phrases
is a list of phrases:
phrases = [process(p) if isinteresting(p) else p for p in phrases]
For a suitable definition of the process
and isinteresting
functions.
A regex-based solution:
>>> import re
>>> phrase = "A lot of interesting and boring words"
>>> regex = re.compile(r"\b(?!(?:interesting|words)\b)\w+\W*")
>>> clean = regex.sub("", phrase)
>>> clean
'interesting words'
The regex works as follows:
\b # start the match at a word boundary
(?! # assert that it's not possible to match
(?: # one of the following:
interesting # "interesting"
| # or
words # "words"
) # add more words if desired...
\b # assert that there is a word boundary after our needle matches
) # end of lookahead
\w+\W* # match the word plus any non-word characters that follow.
精彩评论