python - 改进 for 循环 - 尝试比较 2 个字典列表

标签 python dictionary for-loop lemmatization

我会尽量让自己清楚:我有 5 万条推文,我想对其进行文本挖掘,我想改进我的代码。数据如下所示 (sample_data)。

我有兴趣对我已经清理和标记化的单词进行词形还原(这是 twToken 键的值)

sample_data = [{'twAuthor': 'Jean Lassalle',
                'twMedium': 'iPhone',
                'nFav': None,
                'nRT': '33',
                'isRT': True,
                'twText': ' RT @ColPeguyVauvil : @jeanlassalle "allez aux bouts de vos rêves" ',
                'twParty': 'Résistons!',
                'cleanText': ' rt colpeguyvauvil jeanlassalle allez aux bouts de vos rêves ',
                'twToken': ['colpeguyvauvil', 'jeanlassalle', 'allez', 'bouts', 'rêves']},
               {'twAuthor': 'Jean-Luc Mélenchon',
                'twMedium': 'Twitter Web Client',
                'nFav': '806',
                'nRT': '375',
                'isRT': False,
                'twText': ' (2/2) Ils préfèrent créer une nouvelle majorité cohérente plutôt que les alliances à géométrie variable opportunistes de leur direction. ',
                'twParty': 'La France Insoumise',
                'cleanText': ' 2 2 ils préfèrent créer une nouvelle majorité cohérente plutôt que les alliances à géométrie variable opportunistes de leur direction ',
                'twToken': ['2', '2', 'préfèrent', 'créer', 'nouvelle', 'majorité', 'cohérente', 'plutôt', 'alliances', 'géométrie', 'variable', 'opportunistes', 'direction']},
               {'twAuthor': 'Nathalie Arthaud',
                'twMedium': 'Android',
                'nFav': '37',
                'nRT': '24',
                'isRT': False,
                'twText': ' #10mai Commemoration fin de l esclavage. Reste à supprimer l esclavage salarial defendu par #Macron et Hollande ',
                'twParty': 'Lutte Ouvrière',
                'cleanText': ' 10mai commemoration fin de l esclavage reste à supprimer l esclavage salarial defendu par macron et hollande ',
                'twToken': ['10mai', 'commemoration', 'fin', 'esclavage', 'reste', 'supprimer', 'esclavage', 'salarial', 'defendu', 'macron', 'hollande']
               }]

但是,Python 中没有可靠的法语词形还原器。所以我使用了一些资源来拥有自己的法语单词词形还原器词典。字典看起来像这样:

sample_lemmas = [{"ortho":"rêves","lemme":"rêve","cgram":"NOM"},
                 {"ortho":"opportunistes","lemme":"opportuniste","cgram":"ADJ"},
                 {"ortho":"préfèrent","lemme":"préférer","cgram":"VER"},
                 {"ortho":"nouvelle","lemme":"nouveau","cgram":"ADJ"},
                 {"ortho":"allez","lemme":"aller","cgram":"VER"},
                 {"ortho":"défendu","lemme":"défendre","cgram":"VER"}]

所以 ortho 是单词的书面形式(例如 processed),lemme 是单词的词形还原形式(例如. process) 和 cgram 是单词的语法类别(例如 VER 是动词)。

所以我想做的是为每条推文创建一个 twLemmas 键,它是从 twToken 列表派生的引理列表。所以我循环遍历 sample_data 中的每条推文,然后循环遍历 twToken 中的每个标记,查看标记是否存在于我的引理字典 sample_lemmas 中,如果是,我从 sample_lemmas 字典中检索引理,并将其添加到列表中,该列表将在每个 twLemmas 键中提供。如果没有,我只需将该词添加到列表中即可。

我的代码如下:

list_of_ortho = []                      #List of words used to compare if a token doesn't exist in my lemmas dictionary
for wordDict in sample_lemmas:          #This loop feeds this list with each word
    list_of_ortho.append(wordDict["ortho"])

for elemList in sample_data:            #Here I iterate over each tweet in my data
    list_of_lemmas = []                 #This is the temporary list which will be the value to each twLemmas key
    for token in elemList["twToken"]:   #Here, I iterate over each token/word of a tweet
        for wordDict in sample_lemmas:
            if token == wordDict["ortho"]:
                list_of_lemmas.append(wordDict["lemme"])
        if token not in list_of_ortho:  #And this is to add a word to my list if it doesn't exist in my lemmas dictionary
            list_of_lemmas.append(token)
    elemList["lemmas"] = list_of_lemmas

sample_data

循环工作正常,但需要大约 4 小时才能完成。现在我知道我不是程序员也不是 Python 专家,而且我知道无论如何都需要时间才能完成。然而,这就是为什么我想问你是否有人对我如何改进我的代码有更好的想法?

如果有人能花时间理解我的代码并帮助我,谢谢。我希望我说得足够清楚(抱歉,英语不是我的母语)。

最佳答案

使用将 orthos 映射到 lemmes 的字典:

ortho_to_lemme = {word_dict["ortho"]: word_dict["lemme"] for word_dict in sample_lemmas}
for tweet in sample_data:
    tweet["twLemmas"] = [
        ortho_to_lemme.get(token, token) for token in tweet["twToken"]
    ]

关于python - 改进 for 循环 - 尝试比较 2 个字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148843/

相关文章:

python - 从网站中的警报中获取文本

scala - 使用默认值填充可变映射或替代可变映射以实现 Scala 函数内存

python - 如何按值对字典进行排序并返回格式化字符串列表?

C - For 循环仅针对我修改的数组运行一次

java - 谁能告诉我为什么我的更改数量按钮没有更改数量?

python - zipimporter 找不到/加载子模块

python - 类型错误 : A Future or coroutine is required with AWS lambda

python - 如何使用第二个值对多维进行排序

c# - 字典 trygetvalue null

c - C 中接收相同 ID 的线程