1 回答

TA貢獻1853條經驗 獲得超18個贊
你可以嘗試這樣的事情。
transitions = dict()
in_region = False
reg_end = -1
current_title = None
carmodel = input("input carmodel:")
with open("example.txt","r") as testfile:
content = testfile.readlines()
find_date_line=False
for idx, line in enumerate(content):
if find_date_line:
if line.strip().startswith('/'):
reg_end = idx
find_date_line = False
else:
if line.startswith('Carname'):
#if line.startswith ('Date') within the input 'Carmodel'
#if line.endswith ('/') within the Date region
# Commit last transition before this to dict, if any
if current_title:
transitions[reg_end] = current_title
# add suffix for printing
current_title = 'For rent\n'
elif line.strip().startswith(carmodel):
in_region = True
# This will be overwritten while we remain in the region
# reg_end = idx
find_date_line=True
elif in_region:
in_region = False
if current_title:
transitions[reg_end] = current_title
with open("example.txt", "w") as output:
for idx, line in enumerate(content):
output.write(line)
if idx in transitions:
output.write(transitions[idx])
當你提供輸入時
"Ford Ranger"
輸出文件會像
#Region1 starts here
Carname
"Ford Ranger"
Color "Red"
Mileage "1024"
#Subregion1 starts here
Date
11/02/2018
/
For rent
#Subregion1 ends here
#Region1 ends here
#Add line here "For rent"
#Region2 starts here
Carname
"Toyota Prius"
Color "Red"
Mileage "1024"
#Subregion2 starts here
Date
10/06/2019
/
#Subregion2 ends here
#Region2 ends here
#Add line here "For rent"
添加回答
舉報