gpt4 book ai didi

python - 在 python 列表中查找事件的快速方法

转载 作者:行者123 更新时间:2023-11-28 21:45:00 26 4
gpt4 key购买 nike

我有一组独特的词,叫做h_unique。我还有一个名为 h_tokenized_doc 的二维文档列表,其结构如下:

[ ['hello', 'world', 'i', 'am'], 
['hello', 'stackoverflow', 'i', 'am'],
['hello', 'world', 'i', 'am', 'mr'],
['hello', 'stackoverflow', 'i', 'am', 'pycahrm'] ]

h_unique为:

('hello', 'world', 'i', 'am', 'stackoverflow', 'mr', 'pycharm')

我想要的是在标记化文档列表中找到独特单词的出现。
到目前为止,我想出了这段代码,但这似乎非常很慢。有什么有效的方法可以做到这一点吗?

term_id = []
for term in h_unique:
print term
for doc_id, doc in enumerate(h_tokenized_doc):
term_id.append([doc_id for t in doc if t == term])

在我的例子中,我有一个包含 7000 个文档的文档列表,其结构如下:

[ [doc1], [doc2], [doc3], ..... ]

最佳答案

它会很慢,因为您要为每个唯一的单词遍历整个文档列表一次。为什么不尝试将独特的单词存储在字典中并为找到的每个单词附加到字典中?

unique_dict = {term: [] for term in h_unique}
for doc_id, doc in enumerate(h_tokenized_doc):
for term_id, term in enumerate(doc):
try:
# Not sure what structure you want to keep it in here...
# This stores a tuple of the doc, and position in that doc
unique_dict[term].append((doc_id, term_id))
except KeyError:
# If the term isn't in h_unique, don't do anything
pass

这只遍历所有文档一次。

在您上面的示例中,unique_dict 将是:

{'pycharm': [], 'i': [(0, 2), (1, 2), (2, 2), (3, 2)], 'stackoverflow': [(1, 1), (3, 1)], 'am': [(0, 3), (1, 3), (2, 3), (3, 3)], 'mr': [(2, 4)], 'world': [(0, 1), (2, 1)], 'hello': [(0, 0), (1, 0), (2, 0), (3, 0)]}

(当然假设你的例子中的错字 'pycahrm' 是故意的)

关于python - 在 python 列表中查找事件的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com