替换python代码中的字符串,并在下一行中减量
我想替换Python代码中的字符串。 然后,如果数组中存在x,则减少下一行中的数字,如果数字为零,则删除整行 我的原始文件是:替换python代码中的字符串,并在下一行中减量,python,Python,我想替换Python代码中的字符串。 然后,如果数组中存在x,则减少下一行中的数字,如果数字为零,则删除整行 我的原始文件是: good ${x} hi 1 good ${y} hi 2 good ${z} hi 3 notgood ${t} hi 1 阵列: p0 = [x, y, z] 以及python代码: r = open('replace.txt') o = open('output.txt', 'w+') for line
good ${x}
hi 1
good ${y}
hi 2
good ${z}
hi 3
notgood ${t}
hi 1
阵列:
p0 = [x, y, z]
以及python代码:
r = open('replace.txt')
o = open('output.txt', 'w+')
for line in r:
for i in p0:
if i in line:
line = line.replace("good", "yes")
#line = line + 1
#line = line.replace("2", "1")
x = line
o.write(x)
r.close()
o.close()
当我把这两行放在评论中时,它就起作用了。否则,没有。有人能帮我改进这个代码吗
带着评论
我得到这个结果:
yes ${x}
hi 1
yes ${y}
hi 2
yes ${y}
hi 3
notgood ${t}
hi 1
我的期望和我的努力没有评论:
yes ${x}
yes ${y}
hi 1
yes ${y}
hi 2
notgood ${t}
hi 1
我只想知道一点,不需要整个工作。
谢谢,
增加:
在输入文件中,行可以是:
${x} = Set Variable 1000 // won't change
${x} = Set Variable B // won't change
${t} = Set Variable 1000 // won't change
${t} = Set Variable B // won't change
我想我有点忘乎所以,最终为你写了你的代码 请在下一次发布前阅读,因为这被认为是不礼貌的,否则
def magic(line):
# returns the first number in that line
return [int(s) for s in line.split() if s.isdigit()][0]
p0 = ["x", "y", "z"]
# open the input file
with open('replace.txt') as f:
# read all lines as array
content = f.readlines()
# for all strings we are looking for
for i in p0:
# loop over all lines
j = 0
while j < len(content):
# if the current line contains the word we are looking for
if "${"+i+"}" in content[j]:
# replace "good" with "yes"
content[j] = content[j].replace("good", "yes")
# somehow find the number we want to decrement in the next line
magic_number = magic(content[j+1])-1
if magic_number == 0:
# delete the next line
del content[j+1]
else:
# decrement the number
content[j+1] = content[j+1].replace(str(magic(content[j+1])), str(magic_number))
# skip the second line
j += 1
# go to next line
j += 1
with open('output.txt', "w+") as o:
o.writelines(content)
line=line+1是否会将您带到下一行?你能扩展一下吗?发生了什么?旁注:p0是什么?在我看来,是的,当我把这两行放在评论中时,line=line+1-line=line.replace2,1,它起作用了,它用how you but代替hello,我想在接下来的时间里减少数字line@Fabian这是一个包含x和其他字符串的数组。谢谢@Fabian N。它帮助了我。我在描述中作了修改。像这样更干净。非常感谢你!我不习惯Python语法。我只想使用此行返回intline.split[1]if line.split[0]==text来获取数字,而不是返回[ints for s in line.split if s.isdigit][0],如果第二个字是text。有人有什么想法吗?如果是line,则返回intline.split[1]。split[0]==text else[ints for s in line.split if s.isdigit][0]?但你为什么需要这个?第二行选择第一个数字,新行尝试将第二个单词解析为数字,如果第一个是文本,那么它将返回与第二行相同的结果…谢谢@Fabian N。文件太大了,所以我忘了提及其他细节。你能看到描述中增加的部分吗?像往常一样,只需要一个想法我是Python新手
yes ${x}
yes ${y}
hi 1
yes ${z}
hi 2
notgood ${t}
hi 1