代码之家  ›  专栏  ›  技术社区  ›  Mauro Gentile

考虑报价的字符串拆分

  •  1
  • Mauro Gentile  · 技术社区  · 7 年前

    想象一下这个字符串:

    "a","b","hi, this is Mboyle"
    

    我想用逗号分开,除非逗号在两个引号之间: 即:

    ["a","b","hi, this is Mboyle"]
    

    5 回复  |  直到 7 年前
        1
  •  3
  •   Eugene Primako    7 年前

    你可以不使用逗号,而是使用 "," :

    In [1]: '"a","b","hi, this is Mboyle"'.strip('"').split('","')
    Out[1]: ['a', 'b', 'hi, this is Mboyle']
    
        2
  •  2
  •   Andrej Kesely    7 年前

    我对这个问题的看法(小心使用!)

    s = '"a","b","hi, this is Mboyle"'
    new_s = eval(f'[{s}]')
    print(new_s)
    

    ['a', 'b', 'hi, this is Mboyle']
    

    编辑(更安全的版本):

    import ast.literal_eval
    s = '"a","b","hi, this is Mboyle"'
    new_s = ast.literal_eval(f'[{s}]')
    
        3
  •  1
  •   Mauro Gentile    7 年前

    解决了的。

    with gzip.open(file, 'rt') as handler:
        for row in csv.reader(handler, delimiter=","):
    

        4
  •  1
  •   John Luscombe    7 年前

    你可以在分割中包括报价,所以 .split('","')

        5
  •  1
  •   Ajax1234    7 年前

    你可以用 re.split :

    import re
    s = '"a","b","hi, this is Mboyle"'
    new_s = list(map(lambda x:x[1:-1], re.split('(?<="),(?=")', s)))
    

    输出:

    ['a', 'b', 'hi, this is Mboyle']
    

    然而, re.findall

    new_result = re.findall('"(.*?)"', s)
    

    输出:

    ['a','b','嗨,我是姆博伊尔']