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

运行结果:

相关推荐
薄荷撞~可乐2 分钟前
C#高并发与并行理解处理
开发语言·c#
E___V___E6 分钟前
设计模式--装饰器模式
python·设计模式·装饰器模式
孤廖7 分钟前
【算法磨剑:用 C++ 思考的艺术・Dijkstra 实战】弱化版 vs 标准版模板,洛谷 P3371/P4779 双题精讲
java·开发语言·c++·程序人生·算法·贪心算法·启发式算法
sali-tec12 分钟前
C# 基于halcon的视觉工作流-章33-矩状测量
开发语言·人工智能·算法·计算机视觉·c#
Dan.Qiao30 分钟前
pycharm如何处理python项目间引用
ide·python·pycharm
万粉变现经纪人1 小时前
如何解决pip安装报错ModuleNotFoundError: No module named ‘sympy’问题
python·beautifulsoup·pandas·scikit-learn·pyqt·pip·scipy
酷炫码神1 小时前
第 2 篇:Java 入门实战(JDK8 版)—— 编写第一个 Java 程序,理解基础运行逻辑
java·开发语言·策略模式
像风一样自由20201 小时前
Go语言详细指南:特点、应用场景与开发工具
开发语言·后端·golang
半夏知半秋1 小时前
基于跳跃表的zset实现解析(lua版)
服务器·开发语言·redis·学习·lua
Wyc724091 小时前
Lua语言基础笔记
开发语言·笔记·lua