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

运行结果:

相关推荐
web行路人2 小时前
AI 全栈学习之旅 - Week4:容器化部署与生产环境实战
python·学习
charlie1145141912 小时前
deque、list 与 forward_list:vector 之外的三个选择
开发语言·数据结构·c++·list·开源项目
春涧草茶2 小时前
慢就是快 - 10-2函数 特殊字面量 返回值
python
慢云智慧空间2 小时前
空间智能与计算机视觉的本质差异:不止于识别,更是空间决策能力
人工智能·python·计算机视觉
mayaairi3 小时前
JS DOM属性操作完全指南:内容、样式与自定义属性
开发语言·前端·javascript
avi91113 小时前
Threejs新版本后glb导出提示.x问题GLTFExporter,替代3dmax
开发语言·前端·javascript·threejs·glb·gltfexporter
qq762118223 小时前
windows Qt mingw 编译libzip
开发语言·windows·qt
曹牧3 小时前
Java:Java 数组转 List
java·开发语言·windows
典典分享指南3 小时前
Windows 自动化踩坑实录
python·intellij-idea·pyqt·emacs·visual studio
工业一体机老司机3 小时前
Python实现工业一体机OPC-UA通信:从SDK选型到数据采集实战
开发语言·python·单片机