簡體   English   中英

python中的單詞計數功能

[英]Word counting function in python

我需要在 python 中創建一個名為 word 的函數,它接受一個句子並計算單詞和數字的總數。例如

words('testing 1 2 testing')  

應該回來

{'testing': 2, 1: 1, 2: 1}

我目前正在使用下面的代碼,但輸出將每一件事都作為一個字符串,甚至是數字。

from collections import Counter
def words(sentence):
    return Counter(map(str, sentence.split()))

擴展您的解決方案。 只需在每次迭代中檢查isdigit並相應地執行增量。

s = 'testing 1 2 testing'

d = {}
for word in s.split():
    word = int(word) if word.isdigit() else word
    if word in d:
        d[word] += 1
    else:
        d[word] = 1

將輸出:

{1: 1, 2: 1, 'testing': 2}

暫無
暫無

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

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