我有一个像这样的字符串:
<number>xx<->a<T>b<F>c<F>d<F>e<F>f<F>g<T>h<F>i<F>
我怎样才能有效地解析这个字符串,以便即
xx
的值为null
a
的值为1
b
的值为0
最佳答案
您可以使用正则表达式对其进行解析。我们首先删除开头的<word>
在字符串的开头(如果存在),然后查找 word<word>
对,使用 codes
将它们保存到字典中的键、值对中要转换的字典 _
, F
, T
, 至null
, 0
, 1
。
import re
s = '<number>xx<->a<T>b<F>c<F>d<F>e<F>f<F>g<T>h<F>i<F>'
m = re.match(r'<(\w*?)>', s)
if m:
head = m.group(1)
s = s[m.end():]
print(head)
else:
print('No head group')
codes = {'-': 'null', 'F': '0', 'T': '1'}
pat = re.compile(r'(\w*?)<([-\w]*?)>')
out = {k: codes[v] for k, v in pat.findall(s)}
print(out)
输出
number
{'xx': 'null', 'a': '1', 'b': '0', 'c': '0', 'd': '0', 'e': '0', 'f': '0', 'g': '1', 'h': '0', 'i': '0'}
关于python 字符串标记化 - 自定义词法分析器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47417003/