python - 在列表和字符串中查找匹配的单词

标签 python string performance list comparison

我正在用 Python 编写一些代码,我想检查一个单词列表是否在一个长字符串中。我知道我可以多次迭代它,这可能是同一件事,但我想看看是否有更快的方法。我目前正在做的是:

    all_text = 'some rather long string'
    if "motorcycle" in all_text or 'bike' in all_text or 'cycle' in all_text or 'dirtbike' in all_text:
        print 'found one of em'

但我想做的是:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if item in keyword_list in all_text:
            print 'found one of em'

有没有办法有效地做到这一点?我意识到我可以做到:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
for item in keyword_list:
      if item in all_text:
            print 'found one of em'

但是一旦关键字列表变长,似乎会有更好的方法。

最佳答案

你仍然必须检查它们至少直到在文本中找到一个,但它可以更简洁:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']

if any(word in all_text for word in keyword_list):
    print 'found one of em'

关于python - 在列表和字符串中查找匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14769162/

相关文章:

Python:从 csv 读取时间步长到数组:使用 numpy 后处理模型数据;

python - 用于大规模持久化图形的 NoSQL 解决方案

java - 将所有数据保存在一个文件中还是多个文件中?

python - 为什么字典在某些情况下比 collections.Counter 计数更快?

c++ - 当明确给出数字时,我是否应该引用 std::vector size

python - 比较两个列表中的元素时找到较小的子集

Python 将日期时间设置为 UTC 时区

java - 无法对两个文本字段中的两个数字进行加/减/乘/除操作

c 打印字符串的实际内容

Java:如何将字符串与 toString() 的返回值进行比较