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

运行结果:

相关推荐
凯歌的博客17 分钟前
python虚拟环境应用
linux·开发语言·python
西柚小萌新23 分钟前
【深入浅出PyTorch】--8.1.PyTorch生态--torchvision
人工智能·pytorch·python
MonkeyKing_sunyuhua38 分钟前
can‘t read /etc/apt/sources.list: No such file or directory
python
祈祷苍天赐我java之术41 分钟前
如何在Java中整合Redis?
java·开发语言·redis
多喝开水少熬夜1 小时前
损失函数系列:focal-Dice-vgg
图像处理·python·算法·大模型·llm
froginwe111 小时前
HTML5 测验
开发语言
初学小刘2 小时前
基于 U-Net 的医学图像分割
python·opencv·计算机视觉
B站计算机毕业设计之家2 小时前
Python招聘数据分析可视化系统 Boss直聘数据 selenium爬虫 Flask框架 数据清洗(附源码)✅
爬虫·python·selenium·机器学习·数据分析·flask
雪碧聊技术3 小时前
爬虫是什么?
大数据·爬虫·python·数据分析
FL16238631293 小时前
[yolov11改进系列]基于yolov11使用fasternet_t0替换backbone用于轻量化网络的python源码+训练源码
python·yolo·php