簡體   English   中英

創建詞頻對,保留兩個詞和兩個頻率

[英]Creating word frequency pairs, keeping both words and both frequencies

我有一個冰島語單詞對的列表,它們拼寫相似但意思不同(例如 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))。 我怎樣才能做到這一點?

即使使用您當前的解決方案,您也不需要每次都遍歷整個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM