【发布时间】:2019-08-28 14:25:18
【问题描述】:
我正在从 .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
【问题讨论】:
标签: python-3.x data-extraction