python - 使用python的位置索引

标签 python dictionary indexing

Python 入门。我正在尝试使用嵌套字典实现位置索引。但是我不确定那是否是要走的路。索引应包含术语/术语频率/文档ID/术语位置。

例子:

dict = {term: {termfreq: {docid: {[pos1,pos2,...]}}}}

我的问题是:我是否在正确的轨道上,或者是否有更好的解决方案来解决我的问题。如果嵌套字典是可行的方法,我还有一个额外的问题:如何从字典中获取单个项目:例如一个术语的术语频率(没有关于该术语的所有附加信息)。 非常感谢对此提供帮助。

最佳答案

每个 term 似乎都有一个术语频率、一个文档 ID 和一个位置列表。是对的吗?如果是这样,您可以使用字典的字典:

dct = { 'wassup' : {
            'termfreq' : 'daily',
            'docid' : 1,
            'pos' : [3,4] }}

然后,给定一个术语,例如“wassup”,您可以使用以下命令查找术语频率

dct['wassup']['termfreq']
# 'daily'

将字典想象成电话簿。在给定键(名称)的情况下查找值(电话号码)非常有用。查找给定值的键并不是那么热。当您知道需要单向查找时使用字典。如果您的查找模式更复杂,您可能需要一些其他数据结构(也许是数据库?)。


您可能还想查看 Natural Language Toolkit (nltk) .它有一个 method for calculating tf_idf内置:

import nltk

# Given a corpus of texts
text1 = 'Lorem ipsum FOO dolor BAR sit amet'
text2 = 'Ut enim ad FOO minim veniam, '
text3 = 'Duis aute irure dolor BAR in reprehenderit '
text4 = 'Excepteur sint occaecat BAR cupidatat non proident'

# We split the texts into tokens, and form a TextCollection
mytexts = (
    [nltk.word_tokenize(text) for text in [text1, text2, text3, text4]])
mycollection = nltk.TextCollection(mytexts)

# Given a new text
text = 'et FOO tu BAR Brute'
tokens = nltk.word_tokenize(text)

# for each token (roughly, word) in the new text, we compute the tf_idf
for word in tokens:
    print('{w}: {s}'.format(w = word,
                            s = mycollection.tf_idf(word,tokens)))

产量

et: 0.0
FOO: 0.138629436112
tu: 0.0
BAR: 0.0575364144904
Brute: 0.0

关于python - 使用python的位置索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9210804/

相关文章:

java - 哈希表 "method put() is undefined for the type HashMap"

python - Pandas 数据帧性能

swift - 如何在 Swift 中访问字典中的随机元素

javascript - 按钮数组的当前索引

sql-server - 非聚集索引和覆盖索引的区别

datetime - pandas 日期时间切片 : junkdf. ix ['2015-08-03' :'2015-08-06' ] 不起作用

python - (python)pmdarima.auto_arima(pyramid.auto_arima) 不会自动使用 d 和 D 参数

python - celery-beat KeyError : 'scheduler'

python - 如何修复 `WARNING: erroneous pipeline: no element "疯狂“`

python - 将 Pandas DataFrame 的各个部分 reshape 为宽格式