首页 > 解决方案 > 用单个标签替换字符串中与列表中的条目匹配的任何单词(python)

问题描述

我有一个句子列表(总共约 100k 个句子)和一个“不常用词”列表(长度约 20k)。我想遍历每个句子并用标签“UNK”替换与“infrequent_words”中的条目匹配的任何单词。

(举个小例子,如果

infrequent_words = ['dog','cat']
sentence = 'My dog likes to chase after cars'

然后在应用转换后它应该是

sentence = 'My unk likes for chase after cars'

我很难找到一种有效的方法来做到这一点。下面的这个函数(适用于每个句子)有效,但它很慢,我知道一定有更好的东西。有什么建议么?

def replace_infrequent_words(text,infrequent_words):
    for word in infrequent_words:
        text = text.replace(word,'unk')
    return text

谢谢!

标签: pythonnltk

解决方案


infrequent_words = {'dog','cat'}
sentence = 'My dog likes to chase after cars'

def replace_infrequent_words(text, infrequent_words):
    words = text.split()
    for i in range(len(words)):
        if words[i] in infrequent_words:
            words[i] = 'unk'
    return ' '.join(words)

print(replace_infrequent_words(sentence, infrequent_words))

应该提高性能的两件事:

  1. 使用 aset而不是 alist来存储infrequent_words
  2. 使用 alist来存储每个单词,text这样您就不必在每次替换时扫描整个文本字符串。

这不考虑语法和标点符号,但这应该是您发布的性能改进。


推荐阅读