0

テキスト行を置き換える必要があるテキスト ファイルがあります。

非常に大きなファイルなので、ファイル全体をメモリに読み込むのは最善の方法ではありません。これらのコード ブロックがたくさんありますが、ここにあるのはアイデアを得るための 2 つのみです。私がする必要があるのは置き換える'const/4 v0, 0x1'こと'const/4 v0, 0x0' ですが、メソッドにあるものだけを置き換える必要があるcanCancelFocus()Zので、行を検索して、そのメソッドのを'.method public static canCancelFocus()Z' に置き換える必要があります。'const/4 v0, 0x1''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 に答える