感谢 shlex 这种字符串,我想拆分:
str = 'This doesn''t work' 54e+5 15 .FALSE. 'Another example of "test"'
预期结果:
- 这行不通
- 54e+5
- 15
- .错误。
- “测试”的另一个例子
我的主要问题是语法在带引号的字符串中使用了双单引号 ''。 我无法让 shlex 工作。我尝试了以下设置:
lex = shlex.shlex(str)
lex.whitespace_split = True
lex.quotes = "'"
但即使没有空白字符,它也会在 '' 之间拆分。
谢谢!!
最佳答案
理想情况下,如果您控制文本的生成方式,我会将文件写成 CSV 文件并允许 csv 模块正确引用项目。然后将其读回列表中将是小菜一碟。
但鉴于文本原样,如何:
In [4]: import shlex
In [6]: text = """'This doesn''t work' 54e+5 15 .FALSE. 'Another example of "test"'"""
In [34]: [item.replace('\\"\\"',"''") for item in shlex.split(text.replace("''",'\\"\\"'))]
Out[34]: ["This doesn''t work", '54e+5', '15', '.FALSE.', 'Another example of "test"']
关于Python shlex - 拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16562013/