用引号和逗号解析 csv

Parse csv with quotes and commas

我正在尝试读取 Pandas 中的 csv(通过 read_csv 函数),其中第二个属性 text 包含用双引号封装的字符串。一些示例在字符串中包含更多引号,这些引号被转义,例如"He said \"Okay, I will\" but I doubt it".

e.g. 
  id, text
   0, "random text"
   1, "He said \"Okay, I will\" but I doubt it"

每当我 运行 read_csv 函数时,我都会得到错误 CParserError: Error tokenizing data. C error: Expected 2 fields in line 1, saw 3。这是因为子字符串 \"Okay, I will\" 中的逗号被确认为分隔符,而实际上它不是。

我该如何解决这个问题?


编辑

我在另一个 post 上找到了解决方案。我要做的就是向 read_csv 添加 2 个属性:pd.read_csv('dataset.csv', escapechar='\', encoding='utf-8')。现在一切正常。

您想要 read_csv()quotechar 参数:

The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.

所以添加quotechar='"'.

您显示的文件不正确。引用字段中的引号应该加倍。分隔符后不应出现 space。应该是:

id,text
0,"random text"
1,"He said ""Okay, I will"" but I doubt it"

我在另一个 post 上找到了解决方案。我要做的就是向 read_csv 添加 2 个属性:pd.read_csv('dataset.csv', escapechar='\', encoding='utf-8')。现在一切正常。