我正在尝试创建一个单词字典,其中的单词散列为一个整数以供进一步处理。是否有 defaultdict 的变体,我可以使用它来避免检查 if word not in wordid。这是一个非常大的文件,需要采用省时的方式来执行此操作。
wordid=defaultdict(int)
totaluniquewords = 0
for word in sentencewords:
if word not in wordid:
totaluniquewords+=1
wordid[word]=totaluniquewords
请您参考如下方法:
这里有一个更简单、更快速的方法来获得你想要的东西:
from itertools import count
wordid = dict(zip(set(sentencewords), count(1)))
这使用 set 获取 sentencewords 中的unique 单词,将每个唯一单词与 中的下一个值配对count()(向上计数),并根据结果构建字典。
