【问题标题】:Postings list in PythonPython中的帖子列表
【发布时间】:2021-03-14 18:30:03
【问题描述】:

您好,我需要从多个文件中标记和处理的唯一单词列表中创建一个帖子字典。所以帖子字典的最终格式是: {wordid: [0, 1, ...], wordid2:[0, 1, ...]},

我真的很挣扎,我现在唯一的代码是:

    for i in range(len(docids)):
      for word in vocab:
        if word not in postings.keys():
          postings[word] = []
        else:
          postings[word].append(i)    

这只是输出带有术语的字典,而 docid 只是根据我要求它索引的文件数量以奇怪的模式相互重复。

示例输入和预期输出:
Doc1 = "你好,我的名字是 john",Doc2 = "你好,我的第二个名字是 smith"。
这将创建一个词汇表:['hello', 'my', 'name', 'is', 'john, 'hi', 'second', 'smith']。
每个单词都有一个 wordid 就是这个词的索引

还有一个docid:[0, 1]
(这只是对文档进行计数,并用于创建发布列表以表示:单词w出现在文档doc em>)

这个例子的最终输出是:

postings = {0: [0], 1: [0,1], 2: [0,1], 3: [0,1], 4: [0], 5: [1], 6: [1], 7: [1]}

所以这个 dict 显示了每个 wordid(每个单词在 vocab 中的索引)以及它出现在哪个文档中

整个程序也应该从终端运行,并将目录和文件数量作为参数提供给它。

【问题讨论】:

  • 我完全不明白你的问题......你有什么意见? docidsvocab 包含什么?
  • 这是一个倒排索引(信息检索)问题,其中docid和vocab列表是常用的,docid是一个列表,包含正在读取的文档的所有url和索引。 Vocab 包含了每个文档中的所有单词,重复的单词被去掉了。
  • 如果您可以提供一个带有给定输入(docidsvocabpostings、...)的小示例以及这种情况下的预期输出字典,那将会很有帮助。
  • 谢谢,刚刚添加,希望问题现在更容易理解

标签: python dictionary indexing information-retrieval inverted-index


【解决方案1】:

逐行进行:

for i in range(len(docids)):

您正在超出范围,但数组的内容是[0, 1, ..],您需要将文档添加到postings,而不是它们的索引,所以您应该去:

for docid in docids:

下一个:

  for word in vocab:

由于您希望wordid 成为它在词汇中的索引而不是实际单词本身,因此您应该在此处设置范围或类似的内容(另外,请在 Python 中使用标准缩进 4,几乎其他所有人都这样做):

    for wordid, word in enumerate(vocab):

然后:

        if word not in postings.keys():

如果密钥不存在,您希望添加密钥,如果存在则追加。这就是defaultdict(list) 的用途,所以初始化postings = defaultdict(list),你就不需要接下来的几行了。

最后,您需要检查一个词是否在文档中,但是您没有检查代码来实际检查一个词是否在文档中。由于您已经处理了创建 vocab 的整个文档集,因此再次在每个文档中单独查找每个单词似乎很浪费。

您应该在构建vocab 时构建您的postings

如果您必须这样做,那么迭代保存您的文档的任何内容而不是 docid 更有意义 - 但很难提供有效的代码,因为您没有共享变量的示例值'正在使用。

【讨论】:

    【解决方案2】:

    我想我有你要找的东西,我通过使用字符串列表而不是文件列表稍微简化了问题,但希望你能明白我的出发点。

    # This would be you're list of files
    Docs = [
        "Hello my name is John",
        "Hi my second name is Smith"
    ]
    
    vocab = []
    postings = {}
    for i,doc in enumerate(Docs):
        # if using files for Docs this is 
        # where you read the text from them
        words = doc.split(" ")
        for word in words:
            if word not in vocab:
                vocab.append(word)
            wordId = vocab.index(word)
            if wordId not in postings:
                postings[wordId] = [i]
            else:
                postings[wordId].append(i)
    
    print(postings)
    #{0: [0], 1: [0, 1], 2: [0, 1], 3: [0, 1], 
    # 4: [0], 5: [1], 6: [1], 7: [1]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2023-03-22
      • 2019-07-19
      相关资源
      最近更新 更多