需求:读取word文件,统计python出现的次数
word.txt文件:
方式1
# 读取word文件,统计python单词出现次数
# 方式1
with open("d:/word.txt","r",encoding="UTF-8") as ff:
nr=ff.read()#读取文件所有内容
print(f'python在word文件中出现的次数为:{nr.count('python')}次')#4
运行结果
方式2
# 读取word文件,统计python单词出现次数
# 方式2
count=0
with open("d:/word.txt","r",encoding="UTF-8") as dd:
for s in dd:#s是每一行的 数据
s=s.strip()#不传入参数,是去除首尾空格以及换行符等
words=s.split(' ')# 将字符串转变为 列表 按空格分
for w in words:#遍历列表
if w=='python':
count+=1
print(f'python在word文件中出现的次数为:{count}次')#4
运行结果