简体   繁体   中英

Python csv.reader() to JS?

I have a python code such as :

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 . 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.

[1]: more precisely I look for a JS translation of reader = csv.reader(open('myText.txt', 'r'), delimiter=",") , I can manage the rest.

Note: myText.txt will be this online file

For the given CSV file, I think something like this should suffice (which uses only 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 . Also, you can consider the jQuery-csv library , though it is in 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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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