【发布时间】:2020-05-03 14:28:32
【问题描述】:
我正在尝试编写读取文本文件的代码,并将十六进制数字的每个实例替换为十进制等效值。问题是一旦找到一个十六进制值,代码就会移动到下一行。因此,如果一行中有多个十六进制值,则只有第一个被转换。我是编码新手,通过阅读其他问题/答案,我已经走到了这一步,但我不知道如何让它在每一行上循环,直到它转换了所有的十六进制值。感谢您的帮助。
'''
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)
'''
【问题讨论】: