python - 在 Python 中读取 EEPROM 地址并执行操作
问题描述
我目前正在尝试匹配 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
解决方案
使用正则表达式可以提取文本,也可以通过拆分文本来完成。
正则表达式:
(A1\s+B2)
字符串以A1
+one or more space
+开头B2
(\s+\w+){4}
移动 4 个位置((\s+\w+(\s+\w{4})?){3})
提取3组字符串,组中可能有4个不需要的字符。然后将它们合二为一。
分裂:
注意:如果您有很长的文本或多行,请不要使用这种方式。
text.split("A1 B2")[1]
将文本分成两部分。之后是我们需要的.split()
被空格分割并成为列表['FF', '15', 'A0', '05', 'C2', 'D1', 'E4', '00', '25', '04', '00']
[4:][:3]
移动4个位置,并选择前三个
测试代码:
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']
推荐阅读
- python - 我正在测试使用已弃用功能的代码,但我不确定如何修复它
- python - 如何从不正确的输入向 Django 输入弹出窗口添加 CSS 样式
- haskell - 在我自己的 Queue 类型中包装 Data.Sequence 有什么问题吗?
- c# - 无法在 ListView 中设置相等的行高
- python - Tensorflow 中的执行时间高于 Numpy
- azure - 在 Azure API 管理中重命名出站请求中的查询参数
- r - 在 R 中安装 Caret 包时出现错误消息“系统找不到指定的路径”
- assembly - 指令流水线 - 存储/加载行为如何?
- node.js - Nodejs apis 待处理并在 7 秒后响应
- ubuntu - 如何将 certbot 添加到另一个端口