Python - 将行拆分为列 - csv 数据

Python - Split a row into columns - csv data

我正在尝试从 csv 文件中读取数据,将每一行拆分为相应的列。

但是当特定列本身有 逗号 时,我的正则表达式失败了。

例如:a,b,c,"d,e, g,",f

我想要这样的结果:

a    b    c    "d,e, g,"    f  

这是 5 列。

这是我用来用逗号分割字符串的正则表达式

,(?=(?:"[^"]?(?:[^"])*))|,(?=[^"]+(?:,)|,+|$)

但它对少数字符串无效,而对其他字符串有效。

我要寻找的是,当我使用 pyspark 从 csv 读取数据到 dataframe/rdd 时,我想 load/preserve 所有列都没有任何错误

谢谢

在较新的 regex 模块的帮助下更容易:

import regex as re

string = 'a,b,c,"d,e, g,",f'
rx = re.compile(r'"[^"]*"(*SKIP)(*FAIL)|,')

parts = rx.split(string)
print(parts)
# ['a', 'b', 'c', '"d,e, g,"', 'f']

它支持(*SKIP)(*FAIL)机制,在本例中忽略双引号之间的所有内容。


如果你转义了双引号,你可以使用:

import regex as re

string = '''a,b,c,"d,e, g,",f, this, one, with "escaped \"double",quotes:""'''
rx = re.compile(r'".*?(?<!\)"(*SKIP)(*FAIL)|,')
parts = rx.split(string)
print(parts)
# ['a', 'b', 'c', '"d,e, g,"', 'f', ' this', ' one', ' with "escaped "double",quotes:""']

regex101.com 上查看后者的演示。


近50分,感觉也提供csv方法:

import csv
string = '''a,b,c,"d,e, g,",f, this, one, with "escaped \"double",quotes:""'''

# just make up an iterable, normally a file would go here
for row in csv.reader([string]):
    print(row)
    # ['a', 'b', 'c', 'd,e, g,', 'f', ' this', ' one', ' with "escaped "double"', 'quotes:""']

尝试\,(?=([^"\]*(\.|"([^"\]*\.)*[^"\]*"))*[^"]*$)

已使用 this answer which explains how to match everything that is not in quotes ignoring escaped quotes and http://regexr.com/ 进行测试。

请注意 - 正如对您问题的其他回答所述 - 解析 CSV 的方法比使用正则表达式更好。

您无法使用正则表达式轻松解析 CSV 文件。

我从 Unix 命令行处理 CSV 的首选工具包是 csvkit,您可以从 https://csvkit.readthedocs.io 获得它。它也有一个 Python 库。

标准 csv 库的 Python 文档位于:https://docs.python.org/2/library/csv.html

此处对解析 CSV 进行了广泛讨论:

https://softwareengineering.stackexchange.com/questions/166454/can-the-csv-format-be-defined-by-a-regex

这是一条人迹罕至的道路,库也足够好,您不应该编写自己的代码。