替换python代码中的字符串,并在下一个lin中减量

2024-07-02 11:15:28 发布

您现在位置: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 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

Tags: 文件代码inline评论数字hichange
1条回答
网友
1楼 · 发布于 2024-07-02 11:15:28

我想我有点忘乎所以最后还是为你写了代码。。。你知道吗

请在下一次发布前阅读How to create a Minimal, Complete, and Verifiable example,因为这被认为是不礼貌的,否则。。。你知道吗

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)

这将创建如下所示的输出文件:

yes     ${x}

yes    ${y}
hi    1

yes    ${z}
hi    2

notgood    ${t}
hi    1

相关问题 更多 >