gpt4 book ai didi

python - 编辑 .txt 文件 - 算法不工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:04 24 4
gpt4 key购买 nike

我想用代码自动编辑 .txt 文件。所有包含 victory_points 的内容都应被删除,并在“history={”语句之后以另一种形式输入。但最后,它添加了一个额外的 history={.为什么?

代码:

def überschreiben(filename,vp, capital):
data_out=open(filename,"r")
data_in=open(filename+"_output.txt","w")

vpsegment=False
for line in data_out:
if "\thistory" in line:
data_in.write(line+'\n\t\tvictory_points = { '+str(capital)+' '+str(vp)+' }\n')

if "\t\tvictory_points" in line:
vppivot=line
vpsegment=True

if vpsegment==True:
if "}" in line:
data_in.write("")
vpsegment=False
else:
data_in.write("")
else:
data_in.write(line)
data_in.close()
data_out.close()

输入:

state={
id=1
name="STATE_1" # Corsica
manpower = 322900

state_category = town

history={
owner = FRA
victory_points = { 3838 1 }
buildings = {
infrastructure = 4
industrial_complex = 1
air_base = 1
3838 = {
naval_base = 3
}
}
add_core_of = FRA
}

provinces={
3838 9851 11804
}
}

输出:

[...]

state_category = town

history={

victory_points = { 00001 8 }
history={
owner = FRA
buildings = {
infrastructure = 4
industrial_complex = 1
air_base = 1
3838 = {
naval_base = 3
}
}
add_core_of = FRA
}

provinces={
3838 9851 11804
}
}

第二个history={从哪里来?

最佳答案

让我们看看当您阅读 history{ 行时会发生什么:

if "\thistory" in line:
data_in.write(line+'\n\t\tvictory_points = { '+str(capital)+' '+str(vp)+' }\n')

该行包含“\thisistory”,因此它写入了这些行(它写入了第一个“history{”)和其他内容

if "\t\tvictory_points" in line:
vppivot=line
vpsegment=True

没有任何反应,因为该行不包含“\t\tvictory_points”

if vpsegment==True:
if "}" in line:
data_in.write("")
vpsegment=False
else:
data_in.write("")
else:
data_in.write(line)

vpsegment==False 所以它转到 else 语句并写下 "\thisistory{"

关于python - 编辑 .txt 文件 - 算法不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42137666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com