您好,登錄后才能下訂單哦!
這篇文章主要介紹python如何統(tǒng)計字符串每個單詞出現(xiàn)的次數(shù),文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
統(tǒng)計字符串每個單詞出現(xiàn)的次數(shù)。
def word_amount(sentence):
split_list = sentence.split()
dict_result = {}
for word_name in split_list:
if word_name not in dict_result.keys():
dict_result[word_name] = 1
else:
dict_result[word_name] += 1
return dict_result
if __name__ == '__main__':
sentence = "I can because i think i can"
dict_result = word_amount(sentence)
print(dict_result)
或者:
if __name__ == '__main__':
sentence = "I can because i think i can"
result = {word: sentence.split().count(word) for word in set(sentence.split())}
print(result)
或者:
from collections import Counter
if __name__ == '__main__':
sentence = "I can because i think i can"
counts = Counter(sentence.split())
print(counts)
以上是“python如何統(tǒng)計字符串每個單詞出現(xiàn)的次數(shù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。