0

我有一个文本文件,需要替换一行文本

它是一个非常大的文件,因此将整个文件读入内存并不是最好的方法。这些代码块有很多,这里只有两个来了解一下。我需要做的是替换'const/4 v0, 0x1''const/4 v0, 0x0' 但我只需要替换canCancelFocus()Z方法中的那个,所以我需要搜索该行,'.method public static canCancelFocus()Z' 然后用该方法中'const/4 v0, 0x1'的 with替换'const/4 v0, 0x0'

Textfile.text 包含:

.method public static CancelFocus()Z
    .locals 1

    const/4 v0, 0x1

    return v0
.end method

.method public static FullSize()Z
    .locals 1

    const/4 v0, 0x1

    return v0
.end method 

......
4

2 回答 2

1

这是给你的一些代码:

fp = open("Textfile.text", "r+")

inFunc = False
line = fp.readline()
while line is not None:
    if inFunc and "const/4 v0, 0x1" in line:
        line = line.replace("0x1", "0x0")
        fp.seek(-len(line), 1)
        fp.write(line)
    elif ".method public static canCancelFocus()Z" in line:
        inFunc = True
    elif ".end method" in line:
        inFunc = False
    line = fp.readline()

fp.close()
于 2012-06-25T16:21:52.613 回答
1

您需要使用标志来切换何时进行替换;当你看到这.method条线时设置它,当你看到它时再次重置它.end method

然后,您仅在上下文标志为 True 时查找要修复的行:

with open('textfile.text', 'r+') as tfile:
    incontext = False
    pos = 0
    for line in tfile:
        pos += len(line) # The read-ahead buffer means we can't use relative seeks.

        # Toggle context
        if line.strip().startswith('.method'):
            incontext = True
            continue
        if line.strip().startswith('.end method'):
            incontext = False
            continue

        if incontext and 'const/4 v0, 0x1' in line:
            line = line.replace('0x1', '0x0')
            tfile.seek(pos - len(line))
            tfile.write(line)

请注意,以上内容会就地覆盖文件;这仅在您的替换与替换文本的长度完全相同时才有效。

如果要更改行的长度(更短,更长),则需要将其写入新文件(或sys.stdout):

with open('textfile.text', 'r') as tfile:
    with open('outputfile.text', 'w') as output:
        incontext = False
        for line in tfile:
            # Toggle context
            if line.strip().startswith('.method'):
                incontext = True
            if line.strip().startswith('.end method'):
                incontext = False

            if incontext and 'const/4 v0, 0x1' in line:
                line = line.replace('0x1', '0x0')

            # Write every line to the output file
            output.write(line)
于 2012-06-25T18:18:38.097 回答