python字符串标记化 - 自定义词法分析器?

时间:2017-11-21 15:41:57

标签: python string tokenize lexer

我有一个字符串:

<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

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式解析它。我们首先删除字符串开头的初始<word>(如果存在),然后查找word<word>对,使用codes将它们保存到字典中的键值对中要将_FT转换为null01的词典。

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'}
相关问题