python - 在Python中查找列表中出现的快速方法

标签 python

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

相关文章:

python - 如何在 python 中用一个变量替换 %s

python - 为什么 CherryPy 对象属性在请求之间保持不变?

python - 为什么发送连续的 UDP 消息会导致消息延迟到达?

python - teamplayer 和 pyhook 奇怪地相互作用

python - 使用 whoosh_search 和分页时出现 sqlalchemy 错误

python - 使用 python 从发件人电子邮件地址在 Outlook 中创建规则

python - 如何更改 mySQL 查询结果中的一行?

python - 通过 Mininet python API 设置的带宽不会反射(reflect)在 Opendaylight 中

python - PyParsing:并非所有标记都传递给 setParseAction()

python - 在 Python 中生成和求解同步 ODE