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

运行结果:

相关推荐
wjs20244 分钟前
JavaScript for 循环详解
开发语言
serve the people5 分钟前
tensorflow 零基础吃透:创建 tf.sparse.SparseTensor 的核心方法
人工智能·python·tensorflow
东华万里5 分钟前
第十五讲 指针 从本质吃透 C 语言指针(上)
c语言·开发语言
测试老哥7 分钟前
UI自动化测试—Jenkins配置优化
自动化测试·软件测试·python·测试工具·ui·jenkins·测试用例
曲幽8 分钟前
Python包管理告别龟速下载:uv工具国内镜像与离线安装实战
python·conda·pip·uv·venv·uvx
moxiaoran575310 分钟前
Go 语言指针
开发语言·golang
爱吃大芒果16 分钟前
Flutter 网络请求完全指南:Dio 封装与拦截器实战
开发语言·javascript·flutter·华为·harmonyos
云水木石16 分钟前
Rust 语言开发的 Linux 桌面来了
linux·运维·开发语言·后端·rust
TsengOnce27 分钟前
阿里云ECS多版本JDK切换
java·python·阿里云