【问题标题】:Parse a single CSV string?解析单个 CSV 字符串?
【发布时间】:2016-06-19 18:26:40
【问题描述】:

有没有一种方法可以解析单个逗号分隔的字符串,而无需使用像 csv.reader(..) 这样的花哨的东西?我可以使用split(',') 函数,但是当有效的列值本身包含逗号时,它不起作用。 csv 库有用于解析正确处理上述特殊情况的 CSV 文件的阅读器,但我不能使用它们,因为我只需要解析一个字符串。但是,如果 Python CSV 允许自己解析单个字符串,那么这对我来说就是新闻。

【问题讨论】:

    标签: python python-2.7 parsing csv


    【解决方案1】:

    仔细查看csv 模块的文档,其中 说:

    reader(...)
        csv_reader = reader(iterable [, dialect='excel']
                                [optional keyword args])
            for row in csv_reader:
                process(row)
    
        The "iterable" argument can be any object that returns a line
        of input for each iteration, such as a file object or a list.  The
        optional "dialect" parameter is discussed below.  The function
        also accepts optional keyword arguments which override settings
        provided by the dialect.
    

    所以如果你有字符串:

    >>> s = '"this is", "a test", "of the csv", "parser"'
    

    你想要“一个对象,它为每个对象返回一行输入 迭代”,你可以把你的字符串包装在一个列表中:

    >>> r = csv.reader([s])
    >>> list(r)
    [['this is', 'a test', 'of the csv parser']]
    

    这就是您使用 csv 模块解析字符串的方式。

    【讨论】:

    • 我想使用iter(s) 作为通用迭代器而不是[s](指定一个列表)会更优雅。但你有我的 +1
    • 如果字符串在值内引用了换行符,这可能不起作用; @alecxe 的回答更有意义
    • list(csv.reader(['"this is", "a test", "of the csv", "parser"']))[0] 轰隆隆!
    【解决方案2】:

    您仍然可以使用 csv 解析单个字符串。使用StringIO写入字符串buffer(也称为内存文件):

    import csv
    from StringIO import StringIO
    
    s = "your string"
    buff = StringIO(s)
    
    reader = csv.reader(buff)
    for line in reader:
        print(line)
    

    【讨论】:

    • 对于 Python 3 使用 from io import StringIOhere
    • 但要小心非 ASCII 字符串! '如果使用 [Unicode 和 8 位字符串],则无法解释为 7 位 ASCII(使用第 8 位)的 8 位字符串将导致调用 getvalue() 时引发 UnicodeError。 '
    【解决方案3】:
    >>> import csv
    >>> s = '"Yes, this line",can be, parsed as csv'
    >>> list(csv.reader([s]))[0]
    ['Yes, this line', 'can be', ' parsed as csv']
    >>>
    

    基本上只是上面的@larsks 回答,但更简短,并证明它适用于引号内有逗号的 csv 值。

    如果你给我点赞,也给其他答案点赞。 https://stackoverflow.com/a/35822856/1196339

    【讨论】:

      【解决方案4】:

      Pandas DataFrame 的字符串:

      import pandas as pd
      from io import StringIO
      
      csv_str="Column1,Column2\n1,2\n3,4"
      
      buff = StringIO(csv_str)
      df = pd.read_csv(buff)
      

      数据帧:

      Out[1]: 
         Column1  Column2
               1        2
               3        4
      

      对于其他分隔符,将 delimiter="\t" 之类的内容添加到 read_csv()

      【讨论】:

        猜你喜欢
        • 2017-01-27
        • 1970-01-01
        • 2014-09-17
        • 2021-01-08
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        • 2015-02-16
        • 1970-01-01
        相关资源
        最近更新 更多