Python search and replace not replacing properly

2019-07-22 05:47发布

I have this script that needs to replace a file extension and it is not doing so properly:

import os
import sys

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

whatToLookFor = ["Ca", "Cb", "Cd", "Ce", "Cf", "Cg", "Ch", "Ci", "Cj", "Ck", "Cl", "Cm", "Cn", "Co",
                 "Fa", "Fb", "Fc", "Fd", "Fe", "Ff", "Fg", "Fh", "Fi", "Fk", "Fl", "Fm", "Fn", "Fo", 
                 "Fp", "Ga", "Gb", "Gc", "Gd", "Ge", "Gf", "Gg", "Gh", "Gi", "Gj", "Gk", "Gn", "Ja",
                 "Jb", "Jc", "Jd", "Je", "Jf", "Jg", "Jh", "Jk", "Jl", "Jm", "Fj", "cc", "cb", "cd",
                 "ce", "cf", "cg", "ch", "ci", "cj", "ck", "cl", "cm", "cn", "co", "fa", "fb", "fc",
                 "fd", "fe", "ff", "fg", "fh", "fi", "fk", "fl", "fm", "fn", "fo", "fp", "ga", "gb", 
                 "gc", "gd", "ge", "gf", "gg", "gh", "gi", "gj", "gk", "gn", "ja", "jb", "jc", "jd", 
                 "je", "jf", "jg", "jh", "jk", "jl", "jm", "fj"]

oldFile = open("links.htm", "r")
newFile = open("python test.htm", "w")
buffer = oldFile.read()

for item in whatToLookFor:
    for x in range(0, 80):
        if x < 10:
            buffer = buffer.replace(item + str(x), item.upper() + "-0" + str(x))
        else:
            buffer = buffer.replace(item + str(x), item.upper() + "-" + str(x))

newFile.write(buffer)

oldFile.close()
newFile.close()

The file ff10 is being changed to FF-010 when it should not be. It should be changed to FF-10

3条回答
smile是对你的礼貌
2楼-- · 2019-07-22 05:58

Your

if x < 10:

condition is true for 0-9, and false for 10+. That's why you're getting the wrong behavior on #10. Change it to:

if x <= 10:

You'd be surprised how often this happens, to me at least.

查看更多
别忘想泡老子
3楼-- · 2019-07-22 06:05

The file ff10 is being changed to FF-010 when it should not be. It should be changed to FF-10

For some definition of "should". In fact, your code is recognizing the ff1 part and changing it to FF-01. The extra 0 was already in the buffer.

If you like, you can bang your forehead here --> <--

查看更多
倾城 Initia
4楼-- · 2019-07-22 06:18

Without knowing what your actual input is, it will be very difficult to help, however, I did notice one thing. It looks like you are trying to make sure you have two digit numbers in your buffer (after the item from whatToLookFor).

If that's true, life would probably be easier if you replaced this:

if x < 10:
    buffer = buffer.replace(item + str(x), item.upper() + "-0" + str(x))
else:
    buffer = buffer.replace(item + str(x), item.upper() + "-" + str(x))

With:

sx = str(x)
tmp = sx if len(sx) >= 2 else "0" + sx
buffer = buffer.replace(item + sx, item.upper()+ "-" + tmp)

Or, even better:

buffer = buffer.replace(item + str(x), "%s-%02d" % (item.upper(), int(x)) )
查看更多
登录 后发表回答