如何将逗号分隔的字符串解析为列表(警告)?
我需要能够将像这样的字符串放入:
'''foo, bar, "one, two", three four'''
我
['foo', 'bar', 'one, two', 'three four']
有一种感觉(来自#python 的提示)解决方案将涉及 shlex 模块。
I need to be able to take a string like:
'''foo, bar, "one, two", three four'''
into:
['foo', 'bar', 'one, two', 'three four']
I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这取决于您想要变得多么复杂......您是否想要允许不止一种类型的引用。 转义引号怎么样?
您的语法看起来非常像常见的 CSV 文件格式,Python 标准库支持该格式:
输出:
HTH!
It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes?
Your syntax looks very much like the common CSV file format, which is supported by the Python standard library:
Outputs:
HTH!
shlex 模块解决方案允许转义引号、一个引号转义另一个引号以及 shell 支持的所有奇特内容。
转义引号示例:
The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports.
escaped quotes example:
您可能还需要考虑 csv 模块。 我还没有尝试过,但看起来你的输入数据更接近 CSV,而不是 shell 语法(这是 shlex 解析的)。
You may also want to consider the csv module. I haven't tried it, but it looks like your input data is closer to CSV than to shell syntax (which is what shlex parses).
你可以这样做:
You could do something like this:
如果它不需要很漂亮,这可能会让你上路:
If it doesn't need to be pretty, this might get you on your way:
我想说正则表达式就是您在这里寻找的,尽管我对 Python 的正则表达式引擎不是很熟悉。
假设您使用惰性匹配,您可以在字符串上获取一组匹配项,然后将其放入数组中。
I'd say a regular expression would be what you're looking for here, though I'm not terribly familiar with Python's Regex engine.
Assuming you use lazy matches, you can get a set of matches on a string which you can put into your array.