简体   繁体   English

Python csv.reader()转换为JS吗?

[英]Python csv.reader() to JS?

I have a python code such as : 我有一个python代码,例如:

import csv
reader = csv.reader(open('myText.txt', 'r'), delimiter=",")
for row in reader:
print row[0] + 'is' + row[1] + '</br>'

I look for a similar action/code[1] in JS or JQuery . 在JS或JQuery中寻找类似的action / code [1]。 The name of this action is welcome too. 也欢迎此操作的名称。 I'am exploring JS and wondering if there is a way do get an online/offline csv, parse it, iterate, inject some HTML in my website accordingly. 我正在探索JS,想知道是否有一种方法可以获取在线/离线csv,对其进行解析,进行迭代,并相应地在我的网站中注入一些HTML。

[1]: more precisely I look for a JS translation of reader = csv.reader(open('myText.txt', 'r'), delimiter=",") , I can manage the rest. [1]:更准确地说,我寻找JS的reader = csv.reader(open('myText.txt','r'),delimiter =“,”)的JS翻译,我可以管理其余部分。

Note: myText.txt will be this online file 注意: myText.txt将是此在线文件

For the given CSV file, I think something like this should suffice (which uses only jquery ): 对于给定的CSV文件,我认为这样就足够了(仅使用jquery ):

$.get('/path/to/pinyinipamapping.csv')
.done(function(csvData) {
    var body = $('body');
    csvData.split(/\r\n|\n/).forEach(function (rowStr) {
        if (rowStr[0] != '#') {
            var row = rowStr.split(',');
            body.append('<p>' + row[0] + 'is' + row[1] + '</p>');
        }
    });
});

However, this will not work for quoted commas, etc. 但是,这不适用于带引号的逗号等。

For a more complete CSV parsing look at Javascript code to parse CSV data which uses code from this blog post . 有关更完整的CSV解析,请查看Javascript代码以解析CSV数据 ,该数据使用此博客文章中的代码。 Also, you can consider the jQuery-csv library , though it is in beta. 另外,您可以考虑使用jQuery-csv库 ,尽管它处于beta版本。

For a quick and simple file it could be something like this: (Code inspired by this answer ) 对于一个快速而简单的文件,可能是这样的:(受此答案启发的代码)

 // Put here the url to the file
 url = "https://raw.github.com/cburgmer/cjklib/master/cjklib/data/pinyinipamapping.csv";

    $.ajax({
        type: "GET",
        url: url,
        dataType: "text",
        success: function(data) {processData(data);}
     });


function processData(allText) {
    // Get an array of lines
    var allTextLines = allText.split(/\r\n|\n/);
    // Get the number of columns using the first row
    var entries = allTextLines[0].split(',');
    var lines = [];

    // while there are elements in the row
    while (entries.length>0) {
        // remove that line, split it and store in our array 
        lines.push(entries.shift().split(','));
    }
    // Now do your stuff with the array lines

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM