python - 用单个标签替换字符串中与列表中的条目匹配的任何单词(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
谢谢!
解决方案
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))
应该提高性能的两件事:
- 使用 a
set
而不是 alist
来存储infrequent_words
。 - 使用 a
list
来存储每个单词,text
这样您就不必在每次替换时扫描整个文本字符串。
这不考虑语法和标点符号,但这应该是您发布的性能改进。
推荐阅读
- python - Pycharm 中的代码问题 - CERTIFICATE_VERIFY_FAILED
- python - 本地很好,但在应用引擎上:ModuleNotFoundError: No module named 'google'
- php - 如何使用 php 解码 base64 电子邮件?
- flutter - 如何将数据列表设置为从 api 到单选按钮和 Dropbox?
- android - 构建 CopperheadOS Android。失败:mkbootfs.o
- complexity-theory - 如何找到n值
- python - numpy 中是否有一种方法可以从 3d 数组中计算每个 2d 数组的平均值?
- ssl - 默认虚拟主机的 Qualys SslLabs 报告单个 ip 上的第二个虚拟主机证书的证书不匹配
- c++ - 尝试重载输出运算符时,我无法遍历对象向量
- python - 我不知道我的语音识别程序出了什么问题