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()

运行结果:

相关推荐
Elastic 中国社区官方博客24 分钟前
我们如何通过 70 多个拉取请求,将 OpenTelemetry Java agent 迁移到 invokedynamic
java·大数据·开发语言·elasticsearch·搜索引擎·全文检索·es
tyn18837 分钟前
记录本地安装nacos服务的方法及异常
java·开发语言
步行cgn1 小时前
Spring MVC 视图机制的核心接口与类
java·开发语言·后端·spring·mvc
传奇开心果编程2 小时前
【Rust入门练中学】第5课:引用与借用
开发语言·rust·引用·编程语言理论·通用编程语言·借用
qetfw2 小时前
Bash 变量:export、位置参数与默认值展开验证
linux·开发语言·chrome·bash
爱上纯净的蓝天2 小时前
不用云做 RAG:一个本地笔记问答工具的取舍与坑
python·开源·大模型·rag·本地部署
电子云与长程纠缠2 小时前
UE5魂系游戏开发教程05
开发语言·学习·游戏·ui·ue5
cspttty3 小时前
2027风险管理岗准备路线:数学与应用数学如何补齐金融、SQL与Python
开发语言·python·金融
用户8356290780513 小时前
如何使用 Python 格式化 Excel 单元格中的长文本
后端·python
我命由我123453 小时前
Python 开发 - Python 的 pathlib
java·开发语言·后端·python·学习·java-ee·学习方法