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

运行结果:

相关推荐
weixin_4624462311 分钟前
使用 Tornado + systemd 搭建图片静态服务(imgserver)
开发语言·python·tornado
源码获取_wx:Fegn089511 分钟前
基于springboot + vue小区人脸识别门禁系统
java·开发语言·vue.js·spring boot·后端·spring
别多香了17 分钟前
python基础之面向对象&异常捕获
开发语言·python
春蕾夏荷_72829772518 分钟前
Qt 命令行工具
开发语言·qt
Silence_Jy23 分钟前
Kimi K2技术报告
人工智能·python·深度学习·transformer
AI Echoes27 分钟前
自定义 LangChain 文档加载器使用技巧
数据库·人工智能·python·langchain·prompt·agent
寂寞旅行32 分钟前
java敏感词过滤(sensitive-word)
java·开发语言·word
90后小陈老师33 分钟前
Java项目接入AI大模型的四种方式
java·开发语言·人工智能
wuxuanok33 分钟前
Go——Swagger API文档访问500
开发语言·后端·golang
未来之窗软件服务1 小时前
幽冥大陆(八十五)Python 水果识别ONNX转手机mobile —东方仙盟练气期
开发语言·python·模型训练·仙盟创梦ide·东方仙盟