python - shlex 包含空字符串

标签 python shlex

sample = ",,"
values = shlex.shlex(sample, posix=True)
values.quotes = '"'
values.whitespace = ','
values.whitespace_split = True

received_output = list(values)

在上面的代码示例中,我希望将 ["", "", ""] 作为 received_output 的值,但是 received_output code> 只是一个空列表 []。似乎没有任何关于如何接收这种预期行为的信息。

这与 sample.split(',') 配合使用效果很好,但我更喜欢使用 shlex,因为我有带有标记的复杂句子,如果属于组的一部分(例如纬度,以下示例中的经度)。

另一个例子:

sample = '9267,BELMONT,KEELER,,62.4,35.2,10/01/2012,Weekday,"(41.93897000, -87.73212000)"'

expected_output = ['9267', 'BELMONT', 'KEELER', '', '62.4', '35.2', '10/01/2012', 'Weekday', '(41.93897000, -87.73212000)']
retrieved_output = ['9267', 'BELMONT', 'KEELER', '62.4', '35.2', '10/01/2012', 'Weekday', '(41.93897000, -87.73212000)']

最佳答案

shlex docs状态:

  • It’s not possible to parse empty strings, even if quoted.

如果您想在输出中包含空字符串,shlex 库是不合适的工具。

正如 @PadraicCunningham 在评论中指出的那样,csv (逗号分隔值)库应该可以正常工作:

>>> list(csv.reader(['9267,BELMONT,KEELER,,62.4,35.2,10/01/2012,Weekday,"(41.93897000, -87.73212000)"']))[0]
['9267', 'BELMONT', 'KEELER', '', '62.4', '35.2', '10/01/2012', 'Weekday', '(41.93897000, -87.73212000)']
>>> list(csv.reader([',,']))[0]
['', '', '']

关于python - shlex 包含空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35441818/

相关文章:

python - 如何将每 12 行写入一个新文件

python - shlex.split() 和 re.split() 有什么区别?

python - 使用 shlex.split 时保留引号

python - 关于 tkinter 按钮的基本问题

c# - 如何在 C# 中从 Python 脚本调用特定方法?

python - 在某些位置添加子矩阵

python , Windows : parsing command lines with shlex

python - 如何在 Windows 上引用路径? (类似于 shlex.quote)

python - shlex 保留双引号吗?

python - 从 git 安装时,我可以强制 pip 进行浅表检查吗?