Python shlex - 拆分

标签 python shlex

感谢 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/

相关文章:

python , Windows : parsing command lines with shlex

python - Node.js 的 Shlex 拆分等效项

python - 如何使用不带引号的键从字符串中生成有效的 JSON?

python - 模型 clean() 方法和表单 clean() 方法之间有什么关系吗?

python - 从 pandas.DataFrame 的每一列中获取最大的值

Python 自定义解析器未检测参数

Python:如何在字符串列表中查找匹配最多的字符串

python - 减小 matplotlib 图中的点大小

python - shlex 保留双引号吗?