【问题标题】:Splitting a string using given set of delimiters with including them使用给定的分隔符集拆分字符串并包含它们
【发布时间】: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。

我认为这可能是一种更优雅的方式,我很乐意提供指导。

【问题讨论】:

    标签: python split


    【解决方案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', ')', '{', '}', '}']
    

    在 SYMBOLS 周围放置括号使它们成为正则表达式子组,因此出现在输出中。我们不想包含的 \s(空格)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多