1

我正在尝试用逗号“,”分割字符串

例如:

"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()可以使用该功能,有谁知道我可以做到这一点的方法,也许是正则表达式?

4

4 回答 4

16

您可以将 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']
于 2012-05-19T15:08:26.307 回答
2

使用正则表达式,正如您所要求的:

import re

>>>pattern = re.compile(r"([^',]+,?|'[^']+,?')")
>>>re.findall(pattern, "hi, welcome")
['hi', 'welcome']

>>>re.findall(pattern, "'hi, hello,yes','hello, yes','eat,hello'")
["'hi, hello,yes'", "'hello, yes'", "'eat,hello'"]

>>>re.findall(pattern, "'hi,hi',hi")
 ["'hi,hi'", 'hi']

>>>re.findall(pattern, "'hiello, 332',9")
["'hiello, 332'", '9']

模式的第一部分[^',]+,?,捕获不带引号和不带逗号的段。它的末尾可能有一个逗号,也可能没有(如果它是最后一段)。

第二部分,'[^']+,?',捕获用引号括起来的段。它不应该有更多的内部引号,但它可能有逗号。

于 2012-05-19T16:24:10.617 回答
1

您可以使用带有分隔符和引号字符的csv 阅读器。这似乎与您的期望相符。,'

于 2012-05-19T15:11:40.377 回答
1

直接这样做没有csvre没有问题:

def splitstring(s):
    result = []
    for i, piece in enumerate(s.split("'")):
        if piece:
            if i % 2:  # odd pieces are between quotes
                result.append("'" + piece + "'")
            else:  # even pieces aren't
                for subpiece in piece.split(","):
                    if subpiece:
                        result.append(subpiece)
    return result
于 2012-05-20T00:10:50.240 回答