首页 > 解决方案 > 在 Python 中打印 TXT 中最后出现的单词

问题描述

我正在从 .txt 文件中提取数据,我想在整个文件中获取某个单词的最后一次出现。在这种情况下,我得到了三个单词D / DÑATfno但我只想要每个单词的最后一个并打印它。

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

标签: python-3.xdata-extraction

解决方案


利用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')

推荐阅读