簡體   English   中英

詞頻計數器Python

[英]Word Frequency Counter Python

在必須使用字典並計算每個單詞在許多用戶輸入中出現的次數的練習中苦苦掙扎。 它以一種方式工作,但不會使用戶輸入的每一行中的每個單詞都變得原子化。 因此,與其將“快樂日子”的輸入計算為1 x快樂和1 x天,不如將其設為1 x快樂天。 我已經嘗試過split()和lower(),但是這會將輸入轉換為列表,而我正在努力將列表倒入字典中。

您可能已經猜到了,我是個新手,因此非常感謝所有幫助!

occurrences = {}
while True:
    word = input('Enter line: ')
    word = word.lower() #this is also where I have tried a split()
    if word =='':
        break
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
    print(word, occurrences[word])

編輯

歡呼回應。 最終成為最終解決方案。 他們不擔心大小寫,而是希望最終結果為sort()。

occurrences = {}
while True:
    words = input('Enter line: ')
    if words =='':
        break
    for word in words.split(): 
        occurrences[word]=occurrences.get(word,0)+1
for word in sorted(occurrences):
    print(word, occurrences[word])

幾乎所有的東西都存在,您只想在將單詞添加到字典中時遍歷單詞

occurrences = {}
while True:
    words = input('Enter line: ')
    words = words.lower() #this is also where I have tried a split()
    if words =='':
        break
    for word in words.split(): 
        occurrences[word]=occurrences.get(word,0)+1
    for word in (occurrences):
        print(word, occurrences[word])

此行不會執行:petitions [word] = occurrences.get(word,0)+1

因為如果輸入if,它將轉至中斷處,並且從不執​​行該行。 要使它不在if中,請不要縮進。

通常,已發布代碼的縮進被弄亂了,我想這與您實際代碼中的不完全一樣。

您需要逐行統計還是整體統計? 我猜想要逐行顯示,但是您也可以通過取消注釋以下代碼中的幾行內容來輕松獲得總體統計信息:

# occurrences = dict()  # create a dictionary here if yuo want to have incremental overall stats
while True:
    words = input('Enter line: ')
    if words =='':
        break
    word_list = words.lower().split()
    print word_list
    occurrences = dict()  # create a dict here if you want line by line stats
    for word in word_list:
        occurrences[word] = occurrences.get(word,0)+1

    ## use the lines bellow if you want line by line stats
    for k,v in occurrences.items():
        print k, " X ", v

## use the lines bellow if you want overall stats
# for k,v in occurrences.items():
    # print k, " X ", v

暫無
暫無

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

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