當前位置:成語大全網 - 新華字典 - python中,怎麽做個字典,數句子中單詞出現的次數

python中,怎麽做個字典,數句子中單詞出現的次數

以下是壹種可能的計算方法。

sentence='''by:?William?Shakespeare?From?fairest?creatures?we?desire?increase,That?thereby?beauty's?rose?might?never?die,

But?as?the?riper?should?by?time?decease,

His?tender?heir?might?bear?his?memory;

But?thou,?contracted?to?thine?own?bright?eyes,

Feed'st?thy?light's?flame?with?self-substantial?fuel,

Making?a?famine?where?abundance?lies,

Thyself?thy?foe,?to?thy?sweet?self?too?cruel.

Thout?that?are?now?the?world's?fresh?ornament

And?only?herald?to?the?gaudy?spring,

Within?thine?own?bud?buriest?thy?content

And,?tender?churl,?mak'st?waste?in?niggarding.

Pity?the?world,?or?else?this?glutton?be,

To?eat?the?world's?due,?by?the?grave?and?thee.'''

words=sentence.split()

from?string?import?punctuation

words=[w.strip()?for?w?in?words]

for?p?in?punctuation:

words=[w.strip(p)?for?w?in?words]

diff_words=set(words)

stat={}

for?w?in?diff_words:

stat[w]=words.count(w)

print(stat)