使用JavaScript在CSV中计算行数 [英] Count number of lines in CSV with Javascript

查看:115
本文介绍了使用JavaScript在CSV中计算行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一种方法计算一个.csv文件中的行数,使用Javascript,任何有用的提示或资源,有人可以指示我。

I'm trying to think of a way to count the number of lines in a .csv file using Javascript, any useful tips or resources someone can direct me to?

推荐答案

取决于你的意思是一行。对于简单数量的换行符,Robusto的回答很好。

Depends what you mean by a line. For simple number of newlines, Robusto's answer is fine.

如果你想知道表示多少个CSV数据行,更困难一点,因为CSV字段本身可以包含换行符:

If you want to know how many rows of CSV data that represents, things may be a little more difficult, as a CSV field may itself contain a newline:

field1,"field
two",field3

...是一行,至少在 RFC4180 。 (这是CSV的一个恶劣的功能,有这么多非标准的变体; RFC本身是非常晚的游戏。)

...is one row, at least in CSV as defined by RFC4180. (It's one of the aggravating features of CSV that there are so many non-standard variants; the RFC itself was very late to the game.)

所以,如果你需要

字段可以是raw,或者(如果它包含 \\\
)引用,字段将是:

A field can be raw, or (necessarily if it contains \n or ,) quoted, with " represented as double quotes. So a regex for one field would be:

"([^"]|"")*"|[^,\n]*

,因此对于整行(假设它不为空):

and so for a whole row (assuming it is not empty):

("([^"]|"")*"|[^,\n]*)(,("([^"]|"")*"|[^,\n]*))*\n

获取其中的数字:

var rowsn= csv.match(/(?:"(?:[^"]|"")*"|[^,\n]*)(?:,(?:"(?:[^"]|"")*"|[^,\n]*))*\n/g).length;

如果你足够幸运地处理符合RFC4180建议的CSV变体,在非引用字段中没有字符,您可以使它更具可读性。在之前换行符计算每行中的字符。如果是偶数,你有一条完整的线;如果它是一个奇数,你有一个拆分。

If you are lucky enough to be dealing with a variant of CSV that complies with RFC4180's recommendation that there are no " characters in unquoted fields, you can make this a bit more readable. Split on newlines as before and count the number of " characters in each line. If it's an even number, you have a complete line; if it's an odd number you've got a split.

var lines= csv.split('\n');
for (var i= lines.length; i-->0;)
    if (lines[i].match(/"/g).length%2===1)
        lines.splice(i-1, 2, lines[i-1]+lines[i]);
var rowsn= lines.length;

这篇关于使用JavaScript在CSV中计算行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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