【问题标题】:Replace a part of a String with a certain pattern to another string将具有特定模式的字符串的一部分替换为另一个字符串
【发布时间】:2021-06-20 06:03:24
【问题描述】:

我正在使用 Python 代码尝试修改字符串中的某个模式:

input_name = 'FILE_TO_MODIFY.txt'
output_name = 'FILE_TO_MODIFY_SAIDA.txt'

with open('D:/Users/Drive/SOLVER/PythonDataProcessing/UBX_messages/' + input_name, 'r') as f:
    data = f.read()
f.close()

print(len(data))

for i in range(len(data)):
    if data[i] == ' ' and data[i+1] == '=':
        data[i:i+13].replace(' ', ';')

print(data)

基本上我有一个像这样的大字符串:

    extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_SPI = 0x20910353;          //Output rate of the UBX-MON-COMMS message on port SPI
    extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART1 = 0x20910350;        //Output rate of the UBX-MON-COMMS message on port UART1
    extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART2 = 0x20910351;    //Output rate of the UBX-MON-COMMS message on port UART2

我想像这样删除等号之后的所有值:

    extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_SPI;           //Output rate of the UBX-MON-COMMS message on port SPI
    extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART1;     //Output rate of the UBX-MON-COMMS message on port UART1
    extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART2; //Output rate of the UBX-MON-COMMS message on port UART2

我只需要确定开始字符 'space' 后跟 '=' 和停止字符 ';'并用简单的';'替换此区间内的所有内容。大约有 700 行,所以使用 Python 更容易!我用一个 txt 文件打开代码并将所有内容存储在一个字符串中。我一直在尝试使用 replace() 但它不起作用。 OBS:所有值的大小相同(32 位十六进制值)

【问题讨论】:

  • 请显示一些您正在使用的实际代码。

标签: python arrays string replace


【解决方案1】:

您可以使用正则表达式来做到这一点:

import re

text = [
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_SPI = 0x20910353; //Output rate of the UBX-MON-COMMS message on port SPI",
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART1 = 0x20910350; //Output rate of the UBX-MON-COMMS message on port UART1",
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART2 = 0x20910351; //Output rate of the UBX-MON-COMMS message on port UART2",
]

exp_re = re.compile(r" = 0x[0-9]{8}")

clean_text = []
for line in text:
    clean_line = exp_re.sub("", line)
    clean_text.append(clean_line)
    print(clean_line)

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    相关资源
    最近更新 更多