【问题标题】:Code should replace hex with decimal but after first hex value is found it moves to the next line代码应该用十进制替换十六进制,但在找到第一个十六进制值后,它会移动到下一行
【发布时间】: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)

'''

【问题讨论】:

    标签: python loops replace


    【解决方案1】:

    这部分代码可能看起来像(使用类似于 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)
    

    【讨论】:

      【解决方案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) # ['0x2', '0xF', '0xA']    
      
      for h in hex_vals:
          decimal = int(h, 16)
          line.replace(h, decimal)
      

      【讨论】:

      • 谢谢!这帮助我到达那里。
      猜你喜欢
      • 2018-07-26
      • 2011-12-09
      • 1970-01-01
      • 2018-07-16
      • 2014-08-24
      • 1970-01-01
      • 2016-01-05
      • 2019-01-01
      相关资源
      最近更新 更多