[python每日一练]--0004:统计文档内的单词个数

题目链接:https://github.com/Show-Me-the-Code/show-me-the-code
我的github链接:https://github.com/wjsaya/python_spider_learn/tree/master/python_daily
第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。


思路

  1. 打开文件
  2. 利用re模块的findall方法返回为数组的特性,匹配单个单词
  3. 统计findall方法返回的数组长度即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#coding: utf-8
#Auther: wjsaya
#**第 0004 题:**任一个英文的纯文本文件,统计其中的单词出现的个数。
import re
def file_open(filename):
f = open(filename, 'r').read()
#打开文件
ff = re.findall('([a-zA-Z0-9]+)', f)
#正则匹配,组内为大小写字母加数字,后面限定位数为一位以上
print (ff)
print (len(ff))
if __name__ == "__main__":
file = input("将要统计的文件为:")
file_open(file)
根据re模块的findall查找大小写字母加数字,且为1位以上的字符串。因为fingall返回的为数组,因此直接len即可得出个数。

效果图

0004

0%