简体   繁体   English

用双引号括起来时忽略逗号

[英]Ignore commas when enclosed in double quotes

I'd like to extend the code below so it can take double quotes. 我想扩展下面的代码,以便它可以采用双引号。 For example, the string '303,"Candy, Original",45,19' should return [303,"Candy, Original",45,19] . 例如,字符串'303,"Candy, Original",45,19'应返回[303,"Candy, Original",45,19] Please help. 请帮忙。 Thanks. 谢谢。

def parse(s):
    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

data=[parse(x) for x in myString.split(",")]

The csv module handles quoted commas really well. csv模块非常好地处理引用的逗号。 You may want to try building a parser around that. 您可能想尝试围绕它构建解析器。

import csv
from io import StringIO

def to_numeric(x):
    try:
        return int(x)
    except ValueError:
        pass
    try:
        return float(x)
    except ValueError:
        pass
    return x

def parse_line(s):
    f = StringIO(s)
    f.seek(0)
    reader = csv.reader(f)
    out = next(reader)
    return [to_numeric(x) for x in out]

s = '303,"Candy, Original",45,19'
parse_line(s)
# returns:
[303, 'Candy, Original', 45, 19]

Solution using CSV: 使用CSV解决方案:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> from io import StringIO
>>> csv_string = '303,"Candy, Original",45,19'
>>> csv_file = StringIO(csv_string)
>>> 
>>> reader = csv.reader(csv_file, delimiter=',')
>>> reader.__next__()
['303', 'Candy, Original', '45', '19']

You could then pass each value through an int or float coercion to get the native numerics if needed. 然后,您可以通过intfloat强制传递每个值,以便在需要时获取本机数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM