我有一个 txt 文件,其中包含许多日期,例如 2018 2019 2023。
我想按升序对它们进行排序并打印找到日期的行。要查找文件上的日期,我使用此代码。
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")
现在我想按升序对日期进行排序并打印找到它们的行。预期输出
Found 2018 : the pomerol wine is better in 2018 but... blablabla
Found 2020 : the french wine production is not very efficient in 2020 due to weather condition...
如何对 txt 文件使用排序?
您可以将日期(作为整数)和包含日期的行存储在元组列表中并对元组进行排序。
import os
import re
file = 'wine.txt'
if os.path.isfile(file):
lines_with_dates = [] # A list to store tuples of (date, line) format
with open(file, 'r') as f:
for line in f:
match = re.search(r'\b\d{4}\b', line) # Regular expression for date
if match:
lines_with_dates.append((int(match.group()), line.strip())) # Store date and line
# Sort lines by date
lines_with_dates.sort(key=lambda x: x[0])
# Print sorted lines with dates
for date, line in lines_with_dates:
print(f"Found {date} : {line}")
else:
print("File does not exist")