当前位置: 首页 > news >正文

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

运行结果:

相关文章:

  • Qt 多线程的两种实现方式
  • 表单对象与当前行对象的 区别
  • 基于Spring的forum系统测试报告
  • MYSQL中对行与列的操作
  • 【leetcode刷题日记】lc.238-除自身以外数组的乘积
  • redis 缓存命中率降低,该如何解决?
  • OMNIWeb 数据介绍
  • uniapp用法--uni.navigateTo 使用与参数携带的方式示例(包含复杂类型参数)
  • 合合信息大模型加速器2.0实测:当AI开始“读心术“与“考古“
  • 若依框架二次开发——若依(RuoYi)实现手机号/邮箱/用户名多方式登录
  • 【MySQL基础-18】MySQL字符函数详解:高效处理文本数据的利器
  • 说说Redis的内存淘汰策略?
  • 课程6. 决策树
  • #不同版本下,单元测试的注解使用
  • Mysql从入门到精通day5————子查询精讲
  • 人工智能的未来:从弱 AI 到通用人工智能(AGI)
  • 常用的卷积神经网络及Pytorch示例实现
  • AI+制造的破局之战(上):从技术爆发到价值穿透,谁将率先定义“智能体时代”?
  • 网络架构搭建中的 QinQ 与端口安全策略
  • python采集淘宝拍立淘按图搜索API接口,json数据示例参考
  • 查询网站所有关键词排名/seo推广平台
  • 常德做网站的公司/网络推广策划案
  • 咖啡网站建设市场分析/今日百度小说排行榜风云榜
  • 广州专业做网站的公司/网站建设及推广优化
  • 有专门做英文字幕的网站吗/优秀营销软文100篇
  • 广州正规网站制作维护/软文世界