【问题标题】:Creating word frequency pairs, keeping both words and both frequencies创建词频对,保留两个词和两个频率
【发布时间】:2020-02-04 06:48:40
【问题描述】:

我有一个冰岛语单词对列表,它们拼写相似但意思不同(例如 leyti 和 leiti、kyrkja 和 kirkja)。该列表只是单个元素列表,而不是元组列表(所以只是 [leyti, leiti, kyrkja, kirkja])。我正在使用一个大语料库来获取每个单词的频率,所以我可以得到例如 leyti = 频率 3000、leiti = 频率 500 等。我想在从语料库中获取频率的同时保留这些对。目前我正在遍历单词列表并将每个单词与我从大语料库中获得的频率列表进行比较,这会产生一个 f.ex 字典。 {leyti: 3000, leiti:500} 等等。所以基本上我正在这样做:

def findfreq():
    freqdic = findfreq() # a dictionary with all the words in the corpus and their frequencies
    ywords = listofwords() # the list of words 
    yfreq = {} # resulting dictionary with the word from the wordlist and it's frequency as it is in the corpus
    for i in ywords:
        for key, value in freqdic.items():
            if i == key:
                yfreq[i] = value
    return yfreq

但我不想要一个单独包含所有单词的字典,我想要一些(元组?)代表具有两个频率的对(例如:(leyti:3000, leiti:500),(kyrkja: 400,kirkja:600))。我怎样才能做到这一点?

【问题讨论】:

    标签: python nlp word-frequency


    【解决方案1】:

    即使使用当前的解决方案,您也不需要每次都遍历整个 freqdic,您希望从中获得一个值。你可以这样做:

    for i in ywords:
        yfreq[i] = freqdic[i]
    

    如果您想将单词及其频率放在元组中,您可以简单地执行以下操作:

    def findfreq():
        freqdic = findfreq()
        ywords = listofwords()
        return [(w, freqdic[w]) for w in ywords]
    

    你觉得用索引寻址元组太杂乱了,你可以使用namedtuple

    from collections import namedtuple
    Word = namedtuple('Word', ['form', 'frequency'])
    
    def findfreq():
        freqdic = findfreq()
        return [Word(w, freqdic[w]) for w in listofwords()]
    

    然后,您可以使用点符号访问字段,例如 w.formw.frequency

    【讨论】:

    • :-) 如果您认为答案,请将其标记为已接受,以便其他阅读帖子的人知道这是正确答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2019-01-27
    • 2012-10-10
    • 2023-03-22
    相关资源
    最近更新 更多