【发布时间】:2017-12-23 12:12:05
【问题描述】:
假设我有一个 python 字符串列表。 这些字符串是一种类似 C++ 的语言的标记,我已经对它们进行了部分标记。但我留下了一些尚未标记化的字符串。我有一组必须包含在列表中的语言符号的问题。
例子:
class Test
{
method int foo(boolean a, int b) { }
}
我需要的输出是:
tokens = ['class', 'Test', '{', 'method', 'int', 'foo', '(', 'boolean', 'a', ',', 'int', 'b', ')', '{', '}', '}']
从空格中清除代码后得到的输出:
tokens = ['class', 'Test', '{', 'method', 'int', 'foo(boolean', 'a,', 'int', 'b){', '}', '}']
我使用的代码是使用根据空格分割的部分列表:
def tokenize(self, tokens):
"""
Breaks all tokens into final tokens as needed.
"""
final_tokens = []
for token in tokens:
if not have_symbols(token):
final_tokens.append(token)
else:
current_string = ""
small_tokens = []
for character in token:
if character in SYMBOLS_SET:
if current_string:
small_tokens.append(current_string)
current_string = ""
small_tokens.append(character)
else:
current_string += character
final_tokens = final_tokens + small_tokens
return final_tokens
其中 SYMBOLS_SET 是一组符号:
SYMBOLS_SET = {"{", "}", "(", ")", "[", "]", ".", ",", ";", "+", "-", "*", "/", "&", "|", "<", ">", "=", "~"}
如果 token 具有来自 SYMBOL_SET 的符号,则 have_symbol(token) 方法返回 true,否则返回 false。
我认为这可能是一种更优雅的方式,我很乐意提供指导。
【问题讨论】: