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

运行结果:

相关推荐
Halo_tjn3 分钟前
Java Set集合知识点
java·开发语言·数据结构·windows·算法
郝学胜-神的一滴4 分钟前
Linux多线程编程:深入理解pthread_cancel函数
linux·服务器·开发语言·c++·软件工程
廋到被风吹走4 分钟前
【Java】JPA
java·开发语言·oracle
羸弱的穷酸书生5 分钟前
今天跟 AI学了一手
python
不要em0啦6 分钟前
从0开始学python:声明
python
Trouvaille ~6 分钟前
【C++篇】让错误被温柔对待(下):异常高级特性与最佳实践
运维·开发语言·c++·异常·raii·编程实践·基础入门
没有bug.的程序员7 分钟前
服务治理体系:从零到一的全景落地指南
java·开发语言·数据库·微服务·架构
ha_lydms8 分钟前
4、Spark 函数_m/n/o/p/q/r
大数据·数据库·python·sql·spark·数据处理·dataworks
kylezhao20198 分钟前
C#上位机开发数据持久化:xml数据导入导出
xml·开发语言·c#
2501_9098008113 分钟前
Java多线程
java·开发语言·多线程