You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MicroPython调用re.split报AttributeError,无重复re.py文件

问题:MicroPython中调用re.split()报错AttributeError: 'module' object has no attribute 'split'

环境信息

  • 运行环境:Win7系统,通过Thonny 3.3.13(Python 3.7.9)部署代码到Raspberry Pi Pico(RP2040)
  • MicroPython版本:v1.19.1

测试代码

from machine import Pin, SPI, UART
from array import array
import sys, re, time, math, framebuf

sys.path.append("C:/Source/Pico/SSD1322_SPI_4W")
print(sys.path)
import ssd1322

print("Test print")
s1="123\t123\t123"
s2 = re.split(r'\t', s1)
print(s2)

执行报错信息

MicroPython v1.19.1 on 2022-06-18; Raspberry Pi Pico with RP2040
Type "help()" for more information.
%Run -c $EDITOR_CONTENT ['', '.frozen', '/lib', 'C:/Source/Pico/SSD1322_SPI_4W']
Test print
Traceback (most recent call last):
File "", line 67, in
AttributeError: 'module' object has no attribute 'split'

已尝试的其他写法(均报相同错误)

s2 = re.split(r"[^a-zA-Z0-9_]+", s1)
s2 = re.split(r"[\W]+", s1)

原因分析

MicroPython的re模块是CPython标准re模块的精简版本,受限于Pico的硬件内存资源,裁剪了包括split()在内的不少非核心功能。你可以在Pico的REPL中执行dir(re)查看该模块实际提供的方法,会确认确实没有split属性。

解决办法

方法1:使用字符串原生split()(适用于固定简单分隔符)

如果分隔符是固定的简单字符串(比如制表符\t),直接用字符串自带的split()方法即可,无需依赖re:

s1 = "123\t123\t123"
s2 = s1.split('\t')
print(s2)  # 输出: ['123', '123', '123']

方法2:用re.findall()模拟split(适用于正则匹配的复杂分隔符)

如果需要正则匹配的复杂分隔符,可以通过re.findall()提取所有符合要求的目标片段,间接实现split的效果。比如匹配非字母数字下划线的分隔符:

import re
s1 = "abc123!@#def456$%^ghi"
# 提取所有字母数字下划线片段,等价于用非字母数字下划线分隔
s2 = re.findall(r'[a-zA-Z0-9_]+', s1)
print(s2)  # 输出: ['abc123', 'def456', 'ghi']

方法3:升级MicroPython固件

后续版本的MicroPython(比如v1.20及以后)对re模块做了功能扩展,部分版本已支持re.split(),可以尝试升级Pico上的MicroPython固件来解决问题。

内容的提问来源于stack exchange,提问作者Big Owls

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:27:18