python 統計字符串每個單詞出現的次數


方法一:

sentence = "I can because i think i can"
result = {word: sentence.split().count(word) for word in set(sentence.split())}
print(result)

方法二:

def count(str):
    count_words = str.split()
    count_word = {}
    for word in count_words:
        if word not in count_word.keys():
            count_word[word] = 1
        else:
            count_word[word] += 1
    return count_word

print(count('I can because i think i can'))

方法三:

from collections import Counter

str = 'I can because i think i can'
counts = Counter(str.split())
print(counts)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM