計(jì)算列表中單詞的頻率并按頻率排序我使用的是Python 3.3我需要?jiǎng)?chuàng)建兩個(gè)列表,一個(gè)用于單詞,另一個(gè)用于單詞的頻率。我必須根據(jù)頻率列表對(duì)唯一單詞列表進(jìn)行排序,以便具有最高頻率的單詞在列表中排在第一位。我有文本設(shè)計(jì)但不確定如何在Python中實(shí)現(xiàn)它。到目前為止我找到的方法使用了Counter我們還沒有學(xué)過的字典或字典。我已經(jīng)從包含所有單詞的文件中創(chuàng)建了列表,但不知道如何查找列表中每個(gè)單詞的頻率。我知道我需要一個(gè)循環(huán)才能做到這一點(diǎn),但無(wú)法弄明白。這是基本設(shè)計(jì): original list = ["the", "car",....]
newlst = []
frequency = []
for word in the original list if word not in newlst:
newlst.append(word)
set frequency = 1
else
increase the frequency
sort newlst based on frequency list
3 回答

慕桂英4014372
TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
用這個(gè)
from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})
添加回答
舉報(bào)
0/150
提交
取消