cambaluc的个人博客分享 http://blog.sciencenet.cn/u/cambaluc

博文

Python小例:统计文本中单词出现的频次

已有 2806 次阅读 2019-6-11 09:58 |个人分类:Python|系统分类:教学心得| Python

import re

zen='''

The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

此处略去15行...

Namespaces are one honking great idea -- let's do more of those!

'''

s=re.findall('[a-zA-Z]+',zen)

counts={}

for w in s:

    counts[w]=counts.get(w,0)+1

items=list(counts.items())

items.sort(key=lambda x:x[1],reverse=True)

for i in range(20):

    word,count=items[i]

    print("{0:<15}{1:>5}".format(word,count))


此题综合利用正则式、字典、列表、lambda等,很典型很实用,我出试卷的必考题



https://blog.sciencenet.cn/blog-797552-1184289.html

上一篇:北京胡同(五)_为啥称作“金秋”
下一篇:复变函数w=z^2的图
收藏 IP: 124.64.16.*| 热度|

2 李毅伟 朱晓刚

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-19 18:49

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部