Pyhon统计英文句子中单词出现的次数

2025-12-09 16:55:48

1、打开JetBrains PyCharm软件。

Pyhon统计英文句子中单词出现的次数

2、 在代码编辑区域敲入以下代码

sentence=input("请输入需要统计的英文句子:")


for ch in ",.?!":
   sentence=sentence.replace(ch," "
words=sentence.split()
dicts={}
for word in words:
   if word in dicts:
       dicts[word]+=1
   else:
       dicts[word] = 
items=list(dicts.items()
items.sort(key=lambda x:x[1],reverse=True)
for item in items:
   word,count=item
   print("{:<12}{:>5}".format(word,count))

Pyhon统计英文句子中单词出现的次数

3、本代码的注释如下:

sentence=input("请输入需要统计的英文句子:")


#将文本中涉及的标点用空格替代
for ch in ",.?!":
   sentence=sentence.replace(ch," ")
#利用字典统计词频
words=sentence.split()
dicts={}
for word in words:
   if word in dicts:
       dicts[word]+=1
   else:
       dicts[word] = 1
#对统计结果排序
items=list(dicts.items())
#对单词出现的次数reverse=True降序
items.sort(key=lambda x:x[1],reverse=True)
for item in items:
   word,count=item
   print("{:<12}{:>5}".format(word,count))

Pyhon统计英文句子中单词出现的次数

4、运行结果如下。

Pyhon统计英文句子中单词出现的次数

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢