Python第七章02:文件读取的练习

复制代码
# 文件读取练习题

# 通过windows的文本编辑器软件,将如下内容,复制并保存到:word.txt,文件可以储存在任意位置
"""
   "Whispers of the Wind"

The wind hums soft, a lullaby,
Through branches where the shadows lie.
It carries dreams from far away,
Of sunlit hills and ocean spray.

The leaves, they dance in golden light,
A fleeting waltz, both swift and bright.
The world breathes deep, the air feels new,
A quiet song, for me and you.

The stars above, they blink and gleam,
As whispers weave a tender dream.
Of love that lasts, of time that flies,
Of endless skies and gentle sighs.

So let us walk this path, my friend,
Where every bend leads to no end.
For in this moment, pure and true,
The wind still sings, for me and you.

This poem reflects on nature, time, and connection, using simple yet evocative language.
"""
# 通过文件读取操作,读取此文件,统计"the"单词出现的个数

f = open("D:/文件读取练习题.txt","r",encoding="UTF-8")
# 方式一,通过读取文件后, 字符串.count 操作,统计子字符串出现的次数
print(type(f))
abc = f.read()
num = abc.count("The")
print(f"文件读取练习文档中有{num}个The")
# 方式二,读取内容,一行一行读
# count = 0
# for x in f:
#     x = x.replace("\n","") # 通过 字符串.replace 将\n替换成空格
#     # x = x.strip()  # 通过  字符串.strip 取出首位空格和换行符
#     words = x.split(" ")
#     for word in words:
#         if word == "the":
#             count += 1
# print(f"在文件读取练习题中,有{count}个the")

f.close()

运行结果:

相关推荐
麦麦大数据14 分钟前
F047 vue3+flask微博舆情推荐可视化问答系统
python·flask·知识图谱·neo4j·推荐算法·舆情分析·舆情监测
权泽谦14 分钟前
新世代的 C++:当 ChatGPT 遇上模板元编程
开发语言·c++·chatgpt
MediaTea17 分钟前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask
2501_9411114021 分钟前
C++中的状态模式实战
开发语言·c++·算法
java干货37 分钟前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring
2501_941111821 小时前
使用Python进行网络设备自动配置
jvm·数据库·python
源码之家1 小时前
基于python租房大数据分析系统 房屋数据分析推荐 scrapy爬虫+可视化大屏 贝壳租房网 计算机毕业设计 推荐系统(源码+文档)✅
大数据·爬虫·python·scrapy·数据分析·推荐算法·租房
Dxxyyyy1 小时前
零基础学JAVA--Day34(Map接口+HashTable+HashMap+TreeSet+TreeMap+开发中如何选择集合实现类?(重要))
java·开发语言
源码之家1 小时前
机器学习:基于python租房推荐系统 预测算法 协同过滤推荐算法 房源信息 可视化 机器学习-线性回归预测模型 Flask框架(源码+文档)✅
大数据·python·算法·机器学习·数据分析·线性回归·推荐算法
循环过三天1 小时前
7.7、Python-常用内置函数
笔记·python·学习