【问题标题】:Replace word in string if found in dictionary efficiently如果有效地在字典中找到,则替换字符串中的单词
【发布时间】:2017-06-16 03:10:29
【问题描述】:

我有一个字符串列表、一个单词字典及其替换:

titles = ['The cat in the hat', 'Horton hears a who', \ 
          'Green eggs and ham', 'The butter battle book', 'My book about me']
wlist = {'cat': 'word1', 'hat': 'word2', 'Horton': 'word3', \
         'eggs': 'word4', 'butter': 'word5', 'book': 'word6'}

如果在字符串中找到,我需要用它们对应的值替换字典中作为键出现的单词。
到目前为止,我有以下代码:

for i, book in enumerate(titles):
     for k,v in wlist.items():
         if k in book:
             book = book.replace(k, v)
             titles[i] = book

这给了我输出:

['The word1 in the word2',
 'word3 hears a who',
 'Green word4 and ham',
 'The word5 battle word6',
 'My word6 about me']

有没有更有效(更快)的方法来做到这一点,也许没有两个 for 循环?我实际上拥有的清单很大!

非常感谢!

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    这里有几个想法(以及我的理由)。请根据您的数据衡量它们!

    主要想法是减少 Python 代码以支持 C 实现的 Python 函数,并将数据与哨兵相结合以从缓存中获取帮助。

    第一个想法是将所有字符串组合成一个,用字符串中没有的某种标记值分隔,进行替换,然后再次将它们分开。我认为这可能会更快,因为字符串是不可变的,所以当替换发生时 Python 不会继续重新分配它们(尽管我确信它会保留某种缓存,你可能会重复使用它),你可能会从任何算法中受益优势.replace 可能会给您一个字符串,而您只遍历一个字符串,因此您可能会获得缓存加速。当然,您必须支付合并和分离所有字符串并确保您的标记不在数据中的成本。

    第二个想法(从this article 窃取)是使用正则表达式替换字符串,因此正则表达式库只需使用它使用的任何 C 实现的魔法遍历字符串一次。

    所以,结合这两个想法:

    import re
    
    # I'm using '\n' to join the strings. Of course, if you can control your input,
    # you can just load the list into this format instead of converting it
    titles = '\n'.join(['The cat in the hat', 'Horton hears a who', \
              'Green eggs and ham', 'The butter battle book', 'My book about me'])
    
    wlist = {'cat': 'word1', 'hat': 'word2', 'Horton': 'word3', \
             'eggs': 'word4', 'butter': 'word5', 'book': 'word6'}
    
    robj = re.compile('|'.join(wlist.keys()))
    result = robj.sub(lambda m: wlist[m.group(0)], titles)
    result = result.split('\n') # uncombine
    print(result)
    

    再一次,这实际上是猜测。这些想法中的一个或两个或没有一个可能会有所帮助,或者我可能完全不在左侧领域。一旦你测试它们,我很想看到数字!

    【讨论】:

    猜你喜欢
    • 2018-01-23
    • 2013-02-18
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2012-12-04
    • 2019-01-29
    • 1970-01-01
    相关资源
    最近更新 更多