【发布时间】:2013-03-28 17:52:15
【问题描述】:
我正在尝试在 python 中解析从 GSM 调制解调器接收到的消息。
我有很多消息需要解析。我每隔几个小时左右就会收到新消息。
这是我使用串行对象将数据从调制解调器读取到列表 x 后收到的数据示例。
AT+CMGL="ALL"
+CMGL: 1,"REC READ","+918884100421","","13/04/05,08:24:36+22"
here's message one
+CMGL: 2,"REC READ","+918884100421","","13/04/05,09:40:38+22"
here's message two
+CMGL: 3,"REC READ","+918884100421","","13/04/05,09:41:04+22"
here's message three
+CMGL: 4,"REC READ","+918884100421","","13/04/05,10:04:18+22"
here's message four
+CMGL: 5,"REC READ","+918884100421","","13/04/05,10:04:32+22"
here's message five
.
.
.
.
.
还有很多消息,我这里只列出了五个。
我的主要目的是提取消息的内容,例如我收到的每条消息的“这里是消息一”等等。
这是我现在正在使用的代码。
def reading():
print "Reading all the messages stored on SIM card"
phone.write(b'AT+CMGL="ALL"\r')
sleeps()
x=phone.read(10000)
sleeps()
print x
print "Now parsing the message!"
k="".join(x)
parse(k)
k=""
def parse(k):
m = re.search("\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n",k)
print "6="
print m.group(6)
Phone 是我用来从 GSM 调制解调器读取的串行对象。
这里的m.group(6)是捕获第一条消息“这里是消息一”的消息内容
我怎样才能让它匹配所有消息的内容,而不仅仅是第一个。
我尝试设置多行标志,但没有奏效。也没有使用 re.findall() 代替 re.search()。
re.search 返回的匹配对象也是不可迭代的。
请帮忙。
【问题讨论】:
-
能否请您将接收消息的 Python 程序添加到您的问题中?
标签: python regex parsing gsm at-command