统计《西游记》中大圣出现的次数

需要提前掌握的知识点:
一、文件的打开方式(with open)
二、文件的readlines()方法(返回一个字符串列表)
三、正则表达式re.split()方法分割字符串为字符串列表
四、in关键字来判断一个字符串是否在另外一个字符串中
五、for循环和if语句的灵活运用

import re
with open('./xiyouji.txt','r',encoding = 'utf-8') as f:
	paragraphs = f.readlines()	
'''p通过readlines函数获得了一个列表,西游记全文中的每一段话都是列表中的一个元素
   注意这里段落的分割是根据回车键丫就是'\n'作为标志的
'''	

```python
target = '大圣'
counter= 0
word_num = 0
for paragraph in paragraphs:
	sentences = re.split('。|!|,|:|“|”|?| |;',paragraph)
	#通过正则表达式,用多个分隔符号,分割paragraph中的字符串为字符串列表
	for sentence in sentences:
		sentence = sentence.strip()
		if target in sentence:
			counter += 1
			print(sentence)
print(f'{target}一共出现了{counter}次')

运行结果:
在这里插入图片描述
可以看到,大圣一词在西游记中一共出现了1270次。

当然,我们也可以使用jieba分词来一次性搞定:

import jieba
with open('./xiyouji.txt','r',encoding='utf-8') as f:
	xyj_text = f.read()
word_list = list(jieba.cut(xyj_text))
target = '大圣'
count = 0
for word in word_list:
	if target in word:
		count += 1
print(f'{target}出现的次数是:{count}')

运行的结果为:
在这里插入图片描述

发布了273 篇原创文章 · 获赞 40 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41855010/article/details/105241320