python-3.x - 在 Python 中打印 TXT 中最后出现的单词
问题描述
我正在从 .txt 文件中提取数据,我想在整个文件中获取某个单词的最后一次出现。在这种情况下,我得到了三个单词D / DÑA
,Tfno
但我只想要每个单词的最后一个并打印它。
def extract(in_filename):
if not os.path.exists(in_filename):
print("ERROR: Input file does not exist ❌ ")
sys.exit()
with open(in_filename, 'r') as file:
rows = file.readlines()
for row in rows:
if re.match('D/DÑA', row):
row_parse = row.strip()
print(row_parse)
elif re.match('Tfno', row):
row_parse = row.strip()
print(row_parse)
extract('apd29.txt')
输出是:
D/DÑA: PRUEBA PRUEBITA
Tfno: 666666666
D/DÑA: PRUEBA PRUEBITA
Tfno: 666666666
D/DÑA: PRUEBA PRUEBITA <-- I need this
Tfno: 666666666 <-- I need this
我期望输出:
D/DÑA: PRUEBA PRUEBITA
Tfno: 666666666
解决方案
利用reversed
前任:
def extract(in_filename):
if not os.path.exists(in_filename):
print("ERROR: Input file does not exist ❌ ")
sys.exit()
with open(in_filename, 'r') as file:
rows = file.readlines()
for row in reversed(rows): #!Update
if re.match(r'D/DÑA', row):
row_parse = row.strip()
print(row_parse)
break
extract('apd29.txt')
推荐阅读
- html - primeng 单选按钮活动未居中
- java - 如何在 Intellij Idea-2017.2.5 中更改文件创建的评论日期格式?
- javascript - 将两个动作连接到一个减速器?
- rebus - 使用 Rebus.MessageValidation 包可以进行哪些消息验证?
- ios - CAGradientLayer 位置不正确
- android - Android - RecyclerView 边框线颜色
- vbulletin - 辅助检查/更正 vBulletin 数据库的软件工具
- c# - 后处理:在特定图层上禁用运动模糊
- vb.net - 如何使用 vb.net 根据另一个下拉列表值更改下拉值
- tomcat - 来自 F5 负载均衡器虚拟 IP 时,Tomcat 8.5 不服务 http 请求