python - 创建一个单词字典,作为映射到一组 'documents' 中的实例的键

标签 python dictionary nlp

我需要获取一个元组列表,其中包含经过预处理的句子(0 是与出版物相对应的整数,最后的集合查找句子中的所有唯一单词):

(0, 'political commentators on both sides of the political divide agreed that clinton tried to hammer home the democrats theme that trump is temperamentally unfit with the line about his tweets and nuclear weapons', {'weapons', 'political', 'theme', 'line', 'and', 'sides', 'commentators', 'of', 'tried', 'about', 'is', 'agreed', 'clinton', 'the', 'home', 'to', 'divide', 'tweets', 'that', 'democrats', 'unfit', 'on', 'temperamentally', 'both', 'hammer', 'his', 'nuclear', 'with', 'trump'})

并返回一个字典,其中包含作为键的单词,以及作为值的单词“索引”位置的整数列表。即,如果该句子是列表中的第 12 个,则字典值将在所有当前单词旁边包含 12。

我知道我需要枚举原始文档集,然后从元组中的集合中获取单词,但我很难找到正确的语法来迭代元组中的单词集合。现在我什至不知道从哪里开始。如果您想查看我的代码,了解如何从原始行文档生成元组,请点击此处。

def makeDocuments(文件名):

with open(filename) as f:
    
    g = [l for l in f]

    return [tuple([int(l[0:2]), re.sub(r'\W', ' ',(l[2:-1])), set(re.findall(r'[a-zA-Z%]+', l))]) for l in g]

为我提供了一个测试用例,在搜索给定键时,结果应类似于:

断言索引['幸福'] == [16495,66139,84943, 85998,91589,93472, 120070,133078,193349]

“幸福”一词出现在句子中的这些索引位置处。

最佳答案

解析该字符串很困难,而且您几乎刚刚完成了数据的强力提取。您可以使用 python 的ast 模块来转换文字(您在 python 程序中输入的内容来表示字符串、元组、集合等),而不是尝试猜测这是否适用于所有可能的输入。转换为 python 对象进行处理。之后,只需将新创建的元组中的单词与索引相关联即可。

import ast

def makeDocuments(filename):
    catalog = {}
    with open(filename) as f:
        for line in f:
            index, text, words = ast.literal_eval(line)
            for word in words:
                if word not in catalog:
                    catalog[word] = []
                catalog[word].append(index)
    return catalog

关于python - 创建一个单词字典,作为映射到一组 'documents' 中的实例的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74197478/

相关文章:

python - 编码错误 - xlsxwriter - Python

python - 如何在 xml 文件中搜索单词并在 python 中打印它

c# - 分类或关键字匹配自然语言字符串或短语

machine-learning - scikit加权f1分数计算及使用

python - Cython:将 unicode 字符串转换为 wchar 数组

java - 用于创建工程图的库/语言

python - 将相同的 tkinter 跟踪方法绑定(bind)到多个 tk 变量

python - 根据 'parent' 元组值对字典进行排序

python - 在 Python (pandas) 的多列中进行 Vlookup

C#:从字典中删除重复值?