如何读取带有“?”的CSV行 [英] How to read a CSV line with "?

查看:87
本文介绍了如何读取带有“?”的CSV行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的CSV行可以使用字符串拆分功能。但是一些行可以有,例如

A trivial CSV line could be spitted using string split function. But some lines could have ", e.g.

"good,morning", 100, 300, "1998,5,3"

因此直接使用字符串split不会解决问题。

thus directly using string split would not solve the problem.

我的解决方案是首先使用分割行,然后将字符串与,然后在字符串的开始或结束。

My solution is to first split out the line using , and then combining the strings with " at then begin or end of the string.

这个问题的最佳做法是什么?

What's the best practice for this problem?

我有兴趣,如果有一个Python或F#代码片段。

I am interested if there's a Python or F# code snippet for this.

编辑:我对实现细节感兴趣,而不是使用库。

I am more interested in the implementation detail, rather than using a library.

推荐答案

有一个 csv 模块,它处理这个。

There's a csv module in Python, which handles this.

编辑:这个任务落入 类别。执行这样的任务的标准方法是构建一个状态机(或使用一个lexer库/框架,它将为你做)。

Edit: This task falls into "build a lexer" category. The standard way to do such tasks is to build a state machine (or use a lexer library/framework that will do it for you.)

这个任务的状态机可能只需要两个状态:

The state machine for this task would probably only need two states:


  • 初始一个,它读取除逗号和换行符之外的每个字符作为字段的一部分(异常:尾随空格),逗号作为字段分隔符,换行符作为记录分隔符。当它遇到开头报价时,它会进入

  • read-quoted-field状态,其中不包括引号的每个字符(包括逗号和换行符)都被视为字段的一部分,通过引号表示读引用字段的结束(返回初始状态),引号后面的引号被视为单引号(转义引号)。

顺便说一下,你的连接解决方​​案会在Field1,Field2Field1 Field2

By the way, your concatenating solution will break on "Field1","Field2" or "Field1"",""Field2".

这篇关于如何读取带有“?”的CSV行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆