Skip to main content
 首页 » 编程设计

python之如何解析某些文本数据

2025年05月04日27www_RR

我有一个这样格式的文本文件:

B2100 车门驱动 key 筒开关故障 B2101 头枕开关电路故障 B2102 天线电路接地短路`,再加上 1000 条线。

这就是我想要的样子:

B2100*车门驱动 key 筒开关故障 B2101*头枕开关电路故障 B2102*天线电路对地短路 B2103*天线未连接 B2104*车门乘客 key 锁芯开关故障

这样我就可以在 LibreOffice Calc 中复制这些数据,它会将其格式化为两列代码并分别表示含义。

我的思考过程:
在 Bxxxx 上应用一个正则表达式,并在它前面放一个星号(它充当分隔符)和一个 \n 意思之前(我不知道这是否行得通?),然后删除空格直到遇到下一个字符。

我正在尝试隔离 B2100,但直到现在都失败了。我天真的尝试:

import re 
 
text = """B2100 Door Driver Key Cylinder Switch Failure B2101   Head Rest Switch Circuit Failure B2102  Antenna Circuit Short to Ground B2103   Antenna Not Connected B2104 Door Passenger Key Cylinder Switch Failure B2105    Throttle Position Input Out of Range Low B2106  Throttle Position Input Out of Range High B2107 Front Wiper Motor Relay Circuit Short to Vbatt B2108    Trunk Key Cylinder Switch Failure""" 
# text_arr = text.split("\^B[0-9][0-9][0-9][0-9]$\gi"); 
l = re.compile('\^B[0-9][0-9][0-9][0-9]$\gi').split(text) 
print(l) 

这个输出:

['B2100\tDoor Driver Key Cylinder Switch Failure B2101\tHead Rest Switch Circuit Failure B2102\tAntenna Circuit Short to Ground B2103\tAntenna Not Connected B2104\tDoor Passenger Key Cylinder Switch Failure B2105\tThrottle Position Input Out of Range Low B2106\tThrottle Position Input Out of Range High B2107\tFront Wiper Motor Relay Circuit Short to Vbatt B2108\tTrunk Key Cylinder Switch Failure'] 

如何达到预期的结果?

为了进一步分解,我想做的是:
将所有内容分解为代码 (B1001) 和含义(其后的文本)数组,然后分别对其应用每个操作(\n 事物)。如果您对如何做整件事有更好的想法,那就更好了。我很想听听。

请您参考如下方法:

基本上,您想要:

  • 在输入中找到任何 Bxxxx 字符串。
  • 用换行符替换它们之前的任何空格。
  • 用 * 替换它们之后的任何空格。

这一切都可以用一个re.sub()来完成:

re.sub(r'\s*(B\d{4})\s*', r'\n\1*', text).strip() 

匹配模式:

\s*              # Any amount of whitespace 
   (B\d{4})      # "B" followed by exactly 4 digits 
           \s*   # Any amount of whitespace 

替换模式:

\n               # Newline 
  \1             # The first parenthesized sequence from the matching pattern (B####) 
    *            # Literal "*" 

strip() 的目的是删除任何前导或尾随空格,包括将由第一个 B#### 序列的子部分产生的换行符。