2017-12-23 4 views
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を返します。

私はこれを行うよりエレガントな方法かもしれないと思う、私は指針にはうれしいだろう。

答えて

1
import re 

input = r""" 
class Test 
{ 
    method int foo(boolean a, int b) { } 
}""" 

SYMBOLS_SET = {"{", "}", "(", ")", "[", "]", ".", ",", ";", "+", "-", "*", "/", "&", "|", "<", ">", "=", "~"} 

regexp = r"\s(" + "".join([re.escape(i) for i in SYMBOLS_SET]) + ")" 

splitted = re.split(regexp, input) 
tokens = [x for x in splitted if x not in [None, ""]] 

print(tokens) 

はあなたを与える:

['class', 'Test', '{', 'method', 'int', 'foo', '(', 'boolean', 'a', ',', 'int', 'b', ')', '{', '}', '}'] 

プッシンボルの周りに括弧は、それらの正規表現のサブグループひいては出力に登場することができます。 \ s(空白)は含めたくありません。

関連する問題