Python3 - 如何为奇数和偶数文件用不同的替换文本增量替换多个文件中的文本

Python3 - How to replace text in multiple files incrementally with different replacement text for odd and even numbered files

我有一个名为 p1.html 到 p20.html 的文件目录。每个文件包含相同的两行文本:

abc
xyz

我的目标是将奇数文件(p1.html、p3.html、...)中的文本替换为:

hello
world

并将偶数文件 (p2.html, p4.html, ...) 中的文本替换为:

foo
bar

以下是我最近的尝试。

#!/usr/bin/env python3
import fileinput

def pageseq():

count=1
vtxfile="p%d.html" % count

newopname="hello"
newonname="world"
newepname="foo"
newenname="bar"

for i in range(1, 21):
    if i <= 20 and i % 2 == 0:
        with fileinput.FileInput(vtxfile, inplace=True) as file:
            for line in file:
                line = line.replace('abc', newopname)
                line = line.replace('xyz', newonname)
                print (line, end='')
        fileinput.close()
        count += 1
        
    elif i <= 20 and i % 2 != 0:
        with fileinput.FileInput(vtxfile, inplace=True) as file:
            for line in file:
                line = line.replace('abc', newepname)
                line = line.replace('xyz', newenname)
                print (line, end='')
        fileinput.close()
        count += 1

    else:
        print("Done")

pageseq()

出于某种原因,我无法使用 for 循环打开每个文件并进行增量更改。相反,只有第一个文件 (p1.html) 被修改,其余文件未被修改。

这就是您定义 vtxfile 的方式...vtxfile="p%d.html" % count

count 变量以当前值插入到字符串中,而不是对其的引用。

因此每次更新计数时都需要重新定义vtxfile

将该变量声明放在外循环中将允许它在每次循环运行时更新。但是,既然它在循环内部,您可以只使用循环计数器 i 并删除 count 变量和对它的所有引用。 vtxfile="p%d.html" % i

您也不需要明确关闭文件,因为它会在您离开 with 语句时自动关闭。

还有一些其他的优化可以完成。 if-elsif-else 可以简化为单个 if 语句。

if i <= 20 and i % 2 == 0: 所以在这里,您不需要检查低于 20,因为您限制了循环声明中已经存在的范围,您可以将 if 缩短为 if i%2 == 0:

由于循环条件对于偶数已满,您现在可以将 continue 语句添加到 if 主分支以跳至循环的下一次迭代。

else可以完全删除,因为i永远不会超过20。

在完全删除 else 并将 continue 添加到主 if 之后,我们现在可以将 else if 分支移到 if 逻辑之外,并使它是默认的其他代码。

完整的更新代码。

# Deleted the count and vtxfile lines.

newopname="hello"
newonname="world"
newepname="foo"
newenname="bar"

for i in range(1, 21):
    vtxfile="p%d.html" % i
    if i <= 20 and i % 2 == 0:
        with fileinput.FileInput(vtxfile, inplace=True) as file:
            for line in file:
                line = line.replace('abc', newopname)
                line = line.replace('xyz', newonname)
                print (line, end='')
        continue
        
    with fileinput.FileInput(vtxfile, inplace=True) as file:
        for line in file:
            line = line.replace('abc', newepname)
            line = line.replace('xyz', newenname)
            print (line, end='')

这只是我立即看到的一部分。还有一种方法可以合并两个 with 语句,但我会把它留给你来解决。编码愉快!