我有一组名为 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/