gpt4 book ai didi

python - 在 python 中按 ","拆分

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:20 24 4
gpt4 key购买 nike

我想用逗号“,”分割一个字符串

例如:

"hi, welcome"  I would like to produce ["hi","welcome"]

但是:

"'hi,hi',hi" I would like to produce ["'hi,hi'","hi"]

"'hi, hello,yes','hello, yes','eat,hello'" I would like to produce ["'hi, hello,yes'","'hello, yes'","'eat,hello'"]

"'hiello, 332',9" I would like to produce ["'hiello, 332'","9"]

我不认为可以使用 .split() 函数,有谁知道我可以用正则表达式做到这一点的方法吗?

最佳答案

您可以将 csv 模块与 quotechar 参数一起使用,或者您可以将您的输入转换为使用更标准的 " 字符作为引号字符。

>>> import csv
>>> from cStringIO import StringIO
>>> first=StringIO('hi, welcome')
>>> second=StringIO("'hi,hi',hi")
>>> third=StringIO("'hi, hello,yes','hello, yes','eat,hello'")
>>> fourth=StringIO("'hiello, 332',9")
>>> rfirst=csv.reader(first,quotechar="'")
>>> rfirst.next()
['hi', ' welcome']
>>> rsecond=csv.reader(second,quotechar="'")
>>> rsecond.next()
['hi,hi', 'hi']
>>> rthird=csv.reader(third,quotechar="'")
>>> rthird.next()
['hi, hello,yes', 'hello, yes', 'eat,hello']
>>> rfourth=csv.reader(fourth,quotechar="'")
>>> rfourth.next()
['hiello, 332', '9']

>>> second=StringIO('"hi,hi",hi') # This will be more straightforward to interpret.
>>> r=csv.reader(second)
>>> r.next()
['hi,hi', 'hi']
>>> third=StringIO('"hi, hello,yes","hello, yes","eat,hello"')
>>> r=csv.reader(third)
>>> r.next()
['hi, hello,yes', 'hello, yes', 'eat,hello']

关于python - 在 python 中按 ","拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10666304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com