这是第一次编写的令牌程序的优化版本,它运行得相当好。辅助令牌程序可以解析此函数的输出,以创建具有更大特异性的分类标记。
def tokenize(source):
return (token for token in (token.strip() for line
in source.replace('\r\n', '\n').replace('\r', '\n').split('\n')
for token in line.split('#', 1)[0].split(';')) if token)我的问题是:如何简单地用re模块编写?下面是我无效的尝试。
def tokenize2(string):
search = re.compile(r'^(.+?)(?:;(.+?))*?(?:#.+)?$', re.MULTILINE)
for match in search.finditer(string):
for item in match.groups():
yield item编辑:--这是我从令牌程序中寻找的输出类型。解析文本应该很容易。
>>> def tokenize(source):
return (token for token in (token.strip() for line
in source.replace('\r\n', '\n').replace('\r', '\n').split('\n')
for token in line.split('#', 1)[0].split(';')) if token)
>>> for token in tokenize('''\
a = 1 + 2; b = a - 3 # create zero in b
c = b * 4; d = 5 / c # trigger div error
e = (6 + 7) * 8
# try a boolean operation
f = 0 and 1 or 2
a; b; c; e; f'''):
print(repr(token))
'a = 1 + 2'
'b = a - 3 '
'c = b * 4'
'd = 5 / c '
'e = (6 + 7) * 8'
'f = 0 and 1 or 2'
'a'
'b'
'c'
'e'
'f'
>>> 发布于 2012-08-16 19:13:05
我可能离这里很远-
>>> def tokenize(source):
... search = re.compile(r'^(.+?)(?:;(.+?))*?(?:#.+)?$', re.MULTILINE)
... return (token.strip() for line in source.split('\n') if search.match(line)
... for token in line.split('#', 1)[0].split(';') if token)
...
>>>
>>>
>>> for token in tokenize('''\
... a = 1 + 2; b = a - 3 # create zero in b
... c = b * 4; d = 5 / c # trigger div error
...
... e = (6 + 7) * 8
... # try a boolean operation
... f = 0 and 1 or 2
... a; b; c; e; f'''):
... print(repr(token))
...
'a = 1 + 2'
'b = a - 3'
'c = b * 4'
'd = 5 / c'
'e = (6 + 7) * 8'
'f = 0 and 1 or 2'
'a'
'b'
'c'
'e'
'f'
>>> 如果适用的话,我将把re.compile排除在def范围之外。
发布于 2012-08-16 20:01:23
下面是基于您的tokenize2函数的一个:
def tokenize2(source):
search = re.compile(r'([^;#\n]+)[;\n]?(?:#.+)?', re.MULTILINE)
for match in search.finditer(source):
for item in match.groups():
yield item
>>> for token in tokenize2('''\
... a = 1 + 2; b = a - 3 # create zero in b
... c = b * 4; d = 5 / c # trigger div error
...
... e = (6 + 7) * 8
... # try a boolean operation
... f = 0 and 1 or 2
... a; b; c; e; f'''):
... print(repr(token))
...
'a = 1 + 2'
' b = a - 3 '
'c = b * 4'
' d = 5 / c '
'e = (6 + 7) * 8'
'f = 0 and 1 or 2'
'a'
' b'
' c'
' e'
' f'
>>> https://stackoverflow.com/questions/11993606
复制相似问题