如何对TXT文件中的年份按升序排序并输出对应行?
问题描述
现有一个包含多个4位年份(如2018、2019、2023)的TXT文件,已实现的Python代码能提取文件中的4位年份,但需要优化实现以下需求:
- 将提取到的年份按升序排序
- 输出年份对应的完整行内容,格式要求为:
Found [年份] : [该行完整内容]
原代码如下:
import os import re file='wine.txt' #name of the file if(os.path.isfile(file)): #cheak if file exists or not with open(file,'r') as i: for j in i: #we will travarse line by line in file try: match=re.search(r'\d{4}',j) #regular expression for date print(match.group()) #print date if match is found except AttributeError: pass else: print("file does not exist")
解决方案代码
修改后的代码可以实现排序并按要求格式输出:
import os import re file = 'wine.txt' year_lines = [] if os.path.isfile(file): with open(file, 'r') as f: for line in f: # 去除行尾换行符,避免输出时出现多余空行 cleaned_line = line.rstrip('\n') match = re.search(r'\d{4}', cleaned_line) if match: try: # 将匹配到的年份转为整数,确保排序是数值顺序 year = int(match.group()) year_lines.append((year, cleaned_line)) except ValueError: # 容错处理:理论上\d{4}匹配的是数字,此处做兜底 pass # 按年份升序排序 year_lines.sort(key=lambda x: x[0]) # 按要求格式输出 for year, line in year_lines: print(f"Found {year} : {line}") else: print("file does not exist")
关键修改说明
- 数据存储:新增
year_lines列表,存储(年份整数, 对应行内容)的元组,关联年份和行信息 - 数值转换:把匹配到的年份字符串转为整数,避免字符串排序的潜在问题(比如"0001"和"2018"的字符串排序逻辑不符合数值顺序)
- 排序逻辑:使用列表的
sort()方法,以元组中的年份作为排序依据 - 格式输出:用f-string实现要求的输出格式,同时去除行尾换行符保证输出整洁
- 细节修正:修正原代码中的拼写错误(
cheak→check、travarse→traverse),变量名更具可读性(i→f、j→line)
内容的提问来源于stack exchange,提问作者Damien
相关产品推荐
相关产品推荐

