python - 如果单词列表中的每个单词都存在于具有单词列表作为值的字典中,则返回键
问题描述
我有一个独特的用例。我的主要要求是效率和速度。我有一个长度为40,000的单词列表和一个格式data: {id1: ['hi','how'],id2:['I','love]..}
和长度为250,000的字典。我在这里遇到了很多关于 SO 的问题,但找不到一个可能有效的问题。
如何检查单词列表中的每个单词是否存在于每个字典的单词列表(值)中?通常,可以执行以下操作:
all_words = get_vocabulary(data)
index = {}
for word in all_words:
for doc, tokens in data.items():
if word in tokens :
''' do something with key and tokens'''
通过这样做,我可以检查这个词是否存在,然后做剩下的事情。但是,我的字典和列表很大,这需要很长时间。
如果我必须一遍又一遍地翻阅字典,它显然标志着@DeepSpace在这个问题中提到的问题
我非常感谢您能提供的任何帮助。
解决方案
您可以从字典中创建索引以加快搜索速度。例如:
all_words = ["word1", "word2"]
dct = {
"id1": ["tis", "word1", "and", "word2"],
"id2": ["word3", "word4"],
"id3": ["word2", "only"],
}
# create index dictionary:
index_dct = {}
for k, v in dct.items():
for word in v:
index_dct.setdefault(word, []).append(k)
# index dictionary is:
# {
# "tis": ["id1"],
# "word1": ["id1"],
# "and": ["id1"],
# "word2": ["id1", "id3"],
# "word3": ["id2"],
# "word4": ["id2"],
# "only": ["id3"],
# }
# now the search:
for word in all_words:
if word in index_dct:
for doc in index_dct[word]:
print("Word: {} Doc: {} Tokens: {}".format(word, doc, dct[doc]))
印刷:
Word: word1 Doc: id1 Tokens: ['tis', 'word1', 'and', 'word2']
Word: word2 Doc: id1 Tokens: ['tis', 'word1', 'and', 'word2']
Word: word2 Doc: id3 Tokens: ['word2', 'only']
推荐阅读
- java - 经过几次调试,断点不起作用
- python - 将过滤器应用于表的 Pythonic 方式
- php - WordPress:从内容字段获取所有简码
- python - ConfigObj 将 key=value 更改为我不想的 key = value
- objective-c - 在 Objective-C 和 Swift 中链接可空块?
- reactjs - 我如何以及在哪个文件中在我的服务器 reactJs 上设置缓存控制最大年龄?
- java - 转换列表
到地图 > 列表值作为映射键,映射值带有空列表 java 8 - scala - 如何创建我自己的项目可以依赖的自定义 scalafmt 样式?
- javascript - 如何在超时后杀死 spawnSync
- javascript - 有没有更好的方法来处理来自异步调用的响应而不是执行 setState