Я пытаюсь написать код, который читает текстовый файл, и заменить каждый экземпляр шестнадцатеричного числа на десятичный эквивалент. Проблема в том, что как только шестнадцатеричное значение найдено, код переходит на следующую строку. Таким образом, если в одной строке есть несколько шестнадцатеричных значений, конвертируется только первое. Я новичок в кодировании, и дошел до этого, читая другие вопросы / ответы, но я не знаю, как заставить его зацикливаться на каждой строке, пока он не преобразует все шестнадцатеричные значения. Спасибо за помощь.
«»»
with open(inFileName, 'r') as inFile:
with open(outFileName, 'w') as outFile:
for line in inFile:
if re.search("0[xX][0-9a-fA-F]+",line): # Use regex to search the line for a hex value
hex = re.search("0[xX][0-9a-fA-F]+",line).group() # Get the hex value
dec = int(hex,16) # Convert hex to dec
line_dec = line.replace(hex,str(dec)) # Replace the hex with the dec in the line
outFile.write(line_dec)
else:
outFile.write(line)
«»»
Всего 2 ответа
вместо поиска попробуйте использовать re.findall
import re
line = "0x2 another number 0xF and another 0xA"
hex_vals = re.findall("0[xX][0-9a-fA-F]+", line)
print(hex_vals) # [Ɔx2', ƆxF', ƆxA']
for h in hex_vals:
decimal = int(h, 16)
line.replace(h, decimal)
Эта часть кода может выглядеть (используя что-то похожее на do-while):
actual_fragment = line
found_match = re.search("0[xX][0-9a-fA-F]+",line)
prepared_fragment = ""
while found_match is not None:
hex = found_match.group() # Get the hex value
dec = int(hex,16) # Convert hex to dec
prepared_fragment += actual_fragment[:found_match.start()] + str(dec) # Replace the hex with the dec in the line
actual_fragment = actual_fragment[found_match.end():]
#Very important:
found_match = re.search("0[xX][0-9a-fA-F]+",actual_fragment)
prepared_fragment += actual_fragment
outFile.write(prepared_fragment)