首页 > 解决方案 > 改进 for 循环 - 尝试比较 2 个 dicts 列表

问题描述

我会尽量让自己清楚:我有 50k 条推文我想对其进行文本挖掘,并且我想改进我的代码。数据如下图(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是一个单词的书面形式(例如processes),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 专家,而且我知道无论如何都需要时间来完成。然而,这就是为什么我想问你是否有人对我如何改进我的代码有更好的想法?

如果有人能花时间理解我的代码并帮助我,谢谢。我希望我足够清楚(英语不是我的第一语言对不起)。

标签: pythondictionaryfor-looplemmatization

解决方案


使用将 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"]
    ]

推荐阅读