【发布时间】:2020-04-03 16:01:00
【问题描述】:
我有一个由数字组成的文件 - 文档 ID;和文本 - 文档:
1000 世界末日
1001 这很好
需要创建术语词典和帖子列表。 术语字典表示文档,只是分成术语并与文档 id 配对。术语字典应该是,我猜(key:term,value:document_id)像这样:
=1000
世界 = 1000
结束 = 1000
这 = 1001
是 = 1001
精细 = 1001
Postings 列表表示该术语所在的文档。应该如下所示:
这 = 1000 1001
= 1000 1001
第一个 = 1000
我只是通过将文档拆分为术语而成功(甚至不知道我是否做得对)。下一步该怎么做?
Python 代码
#Open and read documents file
docLine = codecs.open('sample.txt', 'r', 'utf8').read().splitlines()
#Empty dictionary
doc_dictionary = {}
#Split every line in id (keys) and documents (val) to save as dictionary
for document in docLine:
(key, val) = re.split(r'\t+', document)
doc_dictionary[key] = val
print("Documents")
print(doc_dictionary)
#Splits documents into words (terms)
print("")
print("Words")
words = {key: [(val) for val in value.split()] for key, value in doc_dictionary.items()}
print(words)
结果
文档{
“1000”:“古腾堡计划的傲慢与偏见电子书,简·奥斯汀”,
'1001': '这本电子书可供任何人在任何地方免费使用,几乎没有任何限制。您可以根据本电子书随附的 Project Gutenberg 许可条款或在 www.gutenberg.org' 等网站上在线复制、赠送或重新使用它。
单词{
'1000': ['The', 'Project', 'Gutenberg', 'EBook', 'of', 'Pride', 'and', 'Prejudice', 'by', 'Jane', '奥斯汀'],
'1001': ['This', 'eBook', 'is', 'for', 'the', 'use', 'of', 'anyone', 'anywhere', 'at', 'no ', '成本', 'and', 'with', '几乎', 'no', 'restrictions', 'whatever.', 'You', 'may', 'copy', 'it,', 'give ', 'it', 'away', 'or', 're-use', 'it', 'under', 'the', 'terms', 'of', 'the', 'Project', 'Gutenberg ', '许可证', '包含', 'with', 'this', 'eBook', 'or', 'online', 'at', 'www.gutenberg.org'],
【问题讨论】:
标签: python dictionary