В Python, как мы можем открыть текстовый файл и заменить операторы перемещения операциями присваивания? - PullRequest
0 голосов
/ 01 июля 2019

Мы хотим изменить текстовый файл, используя python.В частности, мы хотим заменить строки вида:

MOV al, PTR[esi]

на:

al = PTR[esi]

Это должно работать в целом, а не только для al и PTR[esi].В псевдокоде имеем:

pattern P = "$MOV "
The "$" in pattern P
represents either an empty string
or any character not in {abc...z} or {ABC...Z}

How To Convert Move Statements into Assignment Operations:
    open the file FILE_NAME as FILE
    for each line, LINE, in FILE:
        if LINE matches pattern P:
            do something special
        else:
            print LINE to FILE

How To Do Something Special:
    replace "MOV" with ""
    replace the leftmost comma character with "="
    write modified line to file.     

Ответы [ 2 ]

0 голосов
/ 01 июля 2019

Следующий код безобразен, но выполняет свою работу:

 import re # regular expressions

 with open("write_file.py","w") as outf:
    with open("read_file.asm","r") as inf:
        for line in inf:
            search_target = "(^)([^_a-zA-Z0-9]*)(MOV)( )([a-zA-Z0-9_]+)( *)(,)(.*)"
            result = re.match(search_target, line, flags=re.I)
            if isinstance(result, type(None)):
                print(line, file=outf, end="")
            else:
                groups = [g for g in result.groups()]
                del groups[2]
                del groups[2]
                groups[4] = " = "
                print(''.join(groups), file=outf, end="")
0 голосов
/ 01 июля 2019

Простейшим является line.replace(), например

with open(outfile,"w") as outf:
    with open(infile,"r") as inf:
      for line in inf:
        line = line.replace("MOV","")
        line = line.replace(", "," = ")
        ...
        print(line,file=outf)
...