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_4471952911 分钟前
【无标题】
pytorch·python
迅猛龙办公室14 分钟前
Python实现简单的人名对话
python
阿坨42 分钟前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
老歌老听老掉牙1 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
周杰偷奶茶1 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
happylifetree2 小时前
Python18(补充):练习
python
橙子圆1232 小时前
JUC之集合类不安全
java·开发语言
阿里嘎多学长2 小时前
2026-09-29 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Bruce_Liuxiaowei2 小时前
网页版 DeepSeek “harness desktop“ WebGL 上下文创建失败排查实录
开发语言·javascript·webgl
weixin_416667962 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python