Python:翻译/替换字符串中不是你想要的单词
基本上,我有一堆短语,我只对包含某些单词的短语感兴趣。我想做的是 1)找出该单词是否存在,如果存在,2)删除所有其他单词。我可以用一堆 if 和 for 来做到这一点,但我想知道是否有一种简短/Pythonic 的方法。
Basically, I've got a bunch of phrases and I'm only interested 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建议的算法:
是的,实现此操作将需要“一堆 ifs 和 fors”,但您会惊讶地发现如此容易和这样的逻辑可以清晰地翻译成Python。
实现相同目的的更简洁的方法是使用列表理解,这在一定程度上简化了这个逻辑。鉴于
phrases
是一个短语列表:对于
process
和isinteresting
函数的合适定义。A suggested algorithm:
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:For a suitable definition of the
process
andisinteresting
functions.基于正则表达式的解决方案:
正则表达式的工作原理如下:
A regex-based solution:
The regex works as follows: