越野车文本替换代码:

时间:2011-08-21 19:20:48

标签: python string replace

我似乎无法弄清楚为什么我不断收到这个错误的输出。

输入文件:

ff1
ff2
ff3
ff10
ff11
ff20
ff21
ff23
gb20
gb10
gh23

输出文件:

FF01
FF02
FF03
FF010
FF011
FF020
FF021
FF023
GB020
GB010
GH023

代码:

import os
import sys

#directory is the directory we will work from
directory = "C:\\Users\\user\\Desktop"
os.chdir(directory)

renameWhat = ["ff", "gb", "gh"]

oldFile = open("New Text Document.txt")
buffer = oldFile.read()

for item in renameWhat:
    for i in range(0, 50):
        if i < 10:
            buffer = buffer.replace(item + str(i), item.upper() + "0" + str(i))
        else:
            buffer = buffer.replace(item + str(i), item.upper() + str(i))

outFile = open("test.txt", "w")
outFile.write(buffer)
outFile.close()
oldFile.close()

需要做什么:

我正在尝试将ff替换为大写(完成),然后我需要为所有less than or equal to 9的数字添加零。所以我认为if i is less than 10应该足够好;但这并不是因为它为9以上的所有内容添加了零。我尝试使用len(str(i))来确保它只是长度为1,但仍然无效;我错过了什么?

4 个答案:

答案 0 :(得分:3)

原始解决方案不起作用的原因是它没有检查它是否匹配整行/字/数字。因此,例如在用ff1替换FF01之后,您的缓冲区就是:

FF01
ff2
ff3
FF010
FF011
ff20
ff21
ff23
gb20
gb10
gh23

答案 1 :(得分:2)

这是一个简单的解决方案:

with open("New Text Document.txt") as oldFile:
    with open("test.txt", "w") as outFile:
        for line in oldFile:
            start, end = line[:2], line[2:]
            outfile.write(start.upper() + end.strip().zfill(2) + '\n')

如果您只想大写特定前缀:

with open("New Text Document.txt") as oldFile:
    with open("test.txt", "w") as outFile:
        for line in oldFile:
            start, end = line[:2], line[2:]
            if start in renameWhat:
                start = start.upper()
            outfile.write(start + end.strip().zfill(2) + '\n')

答案 2 :(得分:1)

只需使用zfill string method

>>> str(1).zfill(2)
'01'
>>> str(10).zfill(2)
'10'

答案 3 :(得分:0)

import re
a = """ff1
ff2
ff3
ff10
ff11
ff20
ff21
ff23
gb20
gb10
gh23
"""

regex = re.compile('([a-zA-Z]*)([0-9]*)\n')
b = ""
for i in regex.findall(a):
    if i[0] in ['ff','gb','gh']:
        b+=i[0].upper()
    else:
        b+=i[0]
    if int(i[1]) < 10:
        b+= "0"
    b+= i[1]+"\n"
print b

结果:

FF01
FF02
FF03
FF10
FF11
FF20
FF21
FF23
GB20
GB10
GH23