使用Python创建位置索引
我刚开始学习Python,想用嵌套字典来实现一个位置索引。不过,我不太确定这样做是否合适。这个索引应该包含词语、词频、文档ID和词语的位置。
举个例子:
dict = {term: {termfreq: {docid: {[pos1,pos2,...]}}}}
我的问题是:我这样做对吗?还是说有更好的解决方案?如果嵌套字典是正确的做法,我还有一个额外的问题:我该怎么从字典中提取单个项目?比如说,获取某个词的词频(而不是所有关于这个词的额外信息)。
对此的帮助将不胜感激。
1 个回答
6
每个term
(术语)似乎都有一个出现频率、一个文档ID和一个位置列表。对吗?如果是这样的话,你可以使用字典的字典来存储这些信息:
dct = { 'wassup' : {
'termfreq' : 'daily',
'docid' : 1,
'pos' : [3,4] }}
然后,给定一个术语,比如'wassup',你可以通过以下方式查找它的出现频率:
dct['wassup']['termfreq']
# 'daily'
可以把字典想象成一本电话簿。它非常适合根据名字(键)查找电话号码(值)。但如果你想根据电话号码查找名字,它就不太好用了。当你知道需要单向查找时,使用字典是个好主意。如果你的查找方式更复杂,可能需要其他的数据结构(比如数据库)来处理。
你可能还想看看自然语言工具包(nltk)。它里面有一个计算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