读取Python中的EEPROM地址并进行运算

Reading EEPROM addresses in Python and perform operations

我目前正在尝试匹配 eeprom 转储文本文件的模式以定位某个地址,然后一旦我在搜索中找到就遍历 4 个步骤。我尝试了以下代码来查找模式

regexp_list = ('A1 B2')
line = open("dump.txt", 'r').read()
pattern = re.compile(regexp_list)

matches = re.findall(pattern,line)

for match in matches:
    print(match)

这将扫描 A1 B2 的转储并在​​找到时显示。我需要在 ex 的搜索条件中添加更多这样的地址:'C1 B2', 'D1 F1'。 我尝试将 regexp_list 作为列表而不是元组,但它没有用。

这是问题之一。接下来当我偶然发现搜索时,我想遍历4个地方然后从那里读取地址(见下文)。

输入:

0120   86 1B 00 A1  B2 FF 15 A0  05 C2 D1 E4  00 25 04 00 

在这里,当搜索找到 A1 B2 模式时,我想移动 4 个位置,即从转储中保存来自 C2 D1 E4 的数据。

预期输出:

C2 D1 E4

我希望解释清楚。

#

感谢@kcorlidy

这是我必须输入的最后一段代码,用于删除第一列中的地址。

newtxt = (text.split("A0 05")[1].split()[4:][:5])

for i in newtxt:
    if len(i) > 2:
        newtxt.remove(i)

所以完整的代码看起来像

import re

text = open('dump.txt').read()

regex = r"(A1\s+B2)(\s+\w+){4}((\s+\w{2}(\s\w{4})?){3})"

for ele in re.findall(regex,text,re.MULTILINE):

    print(" ".join([ok for ok in ele[2].split() if len(ok) == 2]))

print(text.split("A1 B2")[1].split()[4:][:5])

#selects the next 5 elements in the array including the address in 1st col
newtxt = (text.split("A1 B2")[1].split()[4:][:5])

for i in newtxt:
    if len(i) > 2:
        newtxt.remove(i)

输入:

0120 86 1B 00 00 C1 FF 15 00 00 A1 B2 00 00 00 00 C2
0130 D1 E4 00 00 FF 04 01 54 00 EB 00 54 89 B8 00 00

输出:

C2 0130 D1 E4 00

C2 D1 E4 00

使用regex可以提取文本,也可以通过拆分文本完成。

正则表达式:

  1. (A1\s+B2) 字符串以 A1 + one or more space + B2
  2. 开头
  3. (\s+\w+){4}移动4个位置
  4. ((\s+\w+(\s+\w{4})?){3}) 提取3组字符串,其中可能有4个不需要的字符。然后合二为一

拆分:

注意:如果您的文本很长或有多行,请不要使用这种方式。

  1. text.split("A1 B2")[1] 将文本分成两部分。后面是我们需要的
  2. .split() 被空格 space 分割成列表 ['FF', '15', 'A0', '05', 'C2', 'D1', 'E4', '00', '25', '04', '00']
  3. [4:][:3]移动4位,select前三位

测试代码:

import re

text = """0120   86 1B 00 A1  B2 FF 15 A0  05 C2 D1 E4  00 25 04 00 
0120 86 1B 00 00 C1 FF 15 00 00 A1 B2 00 00 00 00 C2
0130 D1 E4 00 00 FF 04 01 54 00 EB 00 54 89 B8 00 00 """
regex = r"(A1\s+B2)(\s+\w+){4}((\s+\w{2}(\s\w{4})?){3})"

for ele in re.findall(regex,text,re.MULTILINE):
    #remove the string we do not need, such as blankspace, 0123, \n
    print(" ".join([ok for ok in ele[2].split() if len(ok) == 2]))

print( text.split("A1  B2")[1].split()[4:][:3] )

输出

C2 D1 E4
C2 D1 E4
['C2', 'D1', 'E4']