0
私は文字列の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){', '}', '}']
コードIの使用があります空白に応じて分割された部分リストを使用しています:
SYMBOLS_SETシンボルの集合である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
:トークンがSYMBOL_SETとそうでない場合はfalseからシンボルを持っている場合
SYMBOLS_SET = {"{", "}", "(", ")", "[", "]", ".", ",", ";", "+", "-", "*", "/", "&", "|", "<", ">", "=", "~"}
及び方法have_symbol(トークン)がtrueを返します。
私はこれを行うよりエレガントな方法かもしれないと思う、私は指針にはうれしいだろう。