簡體   English   中英

Python 字數統計實驗室

[英]Python word counting lab

我正在為學校開發這個實驗室,實驗室是這樣的:編寫一個讀取單詞列表的程序。 然后,程序輸出這些單詞及其頻率。

示例:如果輸入是:

hey hi Mark hi mark

output 是:

hey 1
hi 2
Mark 1
hi 2
mark 1

我的代碼是這樣的:

input_stuff = input()
lst = input_stuff.split()

for word in lst:
    print(word, input_stuff.count(word))

它適用於大多數測試,但其中一項已評分測試具有以下輸入:

a cat and a dog may fight but a cat and a cat may fight more

當我用這個輸入運行簡單代碼時,我得到 11 個 'a'; 即使它是一個單詞而不是獨立的,它似乎也在計算它。

我得到的 output 是這樣的:

a 11
cat 3
and 2
a 11
dog 1
may 2
fight 2
but 1
a 11
cat 3
and 2
a 11
cat 3
may 2
fight 2
more 1

為此,您可以使用collections模塊的Counter object:

from collections import Counter

input_list = input().split()

for a in Counter(input_list).most_common():
    print(*a)

因此,輸入a cat and a dog may fight but a cat and a cat may fight more ,這段代碼將產生:

a 4
cat 3
and 2
may 2
fight 2
dog 1
but 1
more 1

你可以試試:

input_stuff = input()
# Get all words
lst = input_stuff.split()

# Get all unique words
lst_set = set(lst)

# Iterate through unique words
for word in lst_set:
    print(word, lst.count(word))

暫無
暫無

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

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