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

运行结果:

相关推荐
加号33 分钟前
【C#】 WebAPI 接口设计与实现指南
开发语言·c#
旦莫6 分钟前
测试工程师如何用AI生成测试用例?我的提示词模板分享
人工智能·python·测试开发·自动化·测试用例·ai测试
lly20240610 分钟前
jQuery 删除元素详解
开发语言
itzixiao11 分钟前
L1-047 装睡 (5分)[java][python]
java·开发语言·python
m0_6138562914 分钟前
Golang怎么实现测试跳过条件_Golang如何根据环境或条件跳过不适用的测试用例【操作】
jvm·数据库·python
林恒smileZAZ19 分钟前
Three.js实现更真实的3D地球[特殊字符]动态昼夜交替
开发语言·javascript·3d
unicrom_深圳市由你创科技26 分钟前
上位机开发常用的语言 / 框架有哪些?
c++·python·c#
abc123456sdggfd35 分钟前
bootstrap如何修改输入框获取焦点时的光晕
jvm·数据库·python
qq_3300379940 分钟前
如何配置ASM元数据备份_md_backup与md_restore重建磁盘组结构
jvm·数据库·python
昭昭日月明44 分钟前
前端仔速通 Python
javascript·python