【问题标题】:Fastest way to compare large strings in python在python中比较大字符串的最快方法
【发布时间】:2018-03-14 07:15:27
【问题描述】:

我有一个单词词典,其频率如下。

mydictionary = {'yummy tim tam':3, 'fresh milk':2, 'chocolates':5, 'biscuit pudding':3}

我有一组字符串如下。

recipes_book = "For today's lesson we will show you how to make biscuit pudding using 
yummy tim tam and fresh milk."

在上面的字符串中,我有字典中的“饼干布丁”、“美味的 tim tam”和“新鲜牛奶”。

我目前正在对字符串进行标记以识别字典中的单词,如下所示。

words = recipes_book.split()
for word in words:
    if word in mydictionary:
        print("Match Found!")

但它只适用于一个单词字典键。因此,我对最快的方法(因为我的真实食谱是非常大的文本)感兴趣,以识别具有多个单词的字典键。请帮帮我。

【问题讨论】:

  • 也许re.findall 是您正在寻找的。或者可能是正则表达式库中的一些其他函数。

标签: python


【解决方案1】:

构建你的正则表达式并编译它。

import re

mydictionary = {'yummy tim tam':3, 'fresh milk':2, 'chocolates':5, 'biscuit pudding':3}

searcher = re.compile("|".join(mydictionary.keys()), flags=re.I | re.S)

for match in searcher.findall(recipes_book):
    mydictionary[match] += 1

之后的输出

{'yummy tim tam': 4, 'biscuit pudding': 4, 'chocolates': 5, 'fresh milk': 3}

【讨论】:

  • 感谢您的出色回答。你能告诉我searcher 行到底发生了什么吗,因为我不太清楚。
  • 可以在那里使用'|'.join(mydictionary) - .format 和 .keys 似乎没有必要......
  • @JonClements 是的。从格式开始,因为我设想使用命名组,但选择退出并且从未简化。
【解决方案2】:

根据一些测试,“in”键比“re”模块快:

What's a faster operation, re.match/search or str.find?

这里的空格没有问题。 假设 mydictionary 是静态的(预定义的),我认为你应该选择相反的东西:

for key in mydictionary.iterkeys():
    if key in recipes_book:
        print("Match Found!")
        mydictionary[key] += 1

在 python2 中,使用 iterkeys 你有一个迭代器,这是一个很好的做法。 使用 python3 你可以直接在字典上循环。

【讨论】:

  • 请注意,在python3中,iterkeys方法不适用于dict数据类型。
【解决方案3】:

通过在大量 str 数据中搜索要查找的文本尝试另一种方式。

import re
for item in mydictionary:
    match = re.search(item, recipes_book, flags=re.I | re.S)
    if match:
       start, end = match.span()
       print("Match found for %s between %d and %d character span" % (match.group(0), start, end))

【讨论】:

  • 当您可以一次搜索任何键时,为什么还要运行多个正则表达式?
  • 是的,你是对的!!!但是,如果您想找到所有匹配的模式怎么办。 “|”一次只会给出一场比赛。
  • 嗯...re.findall('|'.join(mydictionary), recipes_book) 似乎对我有用...因此,如果有人将recipes_book 用作Counter,那么您就可以对其进行.update...
  • 酷。您可以通过多种解决方案获得相同的输出。解决方案取决于用例。就我而言,我还想找到匹配的确切位置(从哪个字符到哪个字符)。 re.findall 没有给出。我只是给出所有匹配的列表。所以基本上,你不能在不了解用例的情况下说一种解决方案比另一种更好。如果 re.findall 适合您,它可能是其他人正在寻找的......但是,如果您只想找到匹配项,我同意 re.findall 也是一个很好的解决方案
  • 当然 - 我只是按照提出问题的人的目的...似乎他们是在发生事件而不是职位...
猜你喜欢
  • 2011-01-04
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
相关资源
最近更新 更多