如何在Python的csv文件中保存带有Unicode字符串的两个列表?

时间:2015-09-12 09:40:56

标签: python list csv unicode arabic

我有一个包含阿拉伯语单词的列表。我将此列表拆分为两个列表,我试图将它们保存到CSV文件中的单独列中:

import csv   
words = ['يعمل','في','جامعة']
tags = ['verb','prep','noun']
with open('results.csv','w', encoding = 'utf-16') as outfile:
    rowlists = zip(words, tags)
    writer = csv.writer(outfile)
    for row in rowlists:
        writer.writerows(row)

上面的代码输出如下:

csv_ouput1

如果用writer.writerows(rowlists)替换for循环,事情会好一点:

enter image description here

但是,所有这些都集中在一栏中。如果第一个列表是英文(删除编码后),相同的代码工作正常。我怀疑zip功能在使用Unicode方面遇到了麻烦,但我不确定。关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:2)

这种情况下的主要问题不是文本的编码,而是writer.writerows函数中传递的内容。 zip()函数返回元组列表。 writerows函数在提供列表时将文本拆分为不同的列。

因此,不要传递元组传递列表

# coding=utf-8
import csv   
words = ['يعمل','في','جامعة']
tags = ['verb','prep','noun']
with open('results.csv','w') as outfile:
    rowlists = zip(words, tags)
    writer = csv.writer(outfile)
    for row in rowlists:
        writer.writerows([row])

答案 1 :(得分:1)

只需将writer.writerow更改为# coding=utf-8 import csv words = ['يعمل','في','جامعة'] tags = ['verb','prep','noun'] with open('results.csv', 'w', encoding = 'utf-16', newline='') as outfile: rowlists = zip(words, tags) writer = csv.writer(outfile) for row in rowlists: writer.writerow(row)

即可
 $(document).ready(function () {
 $("#art").click(function () {
 $("#art_pop").fadeIn(300);
 });

 $(".pop > span, .pop").click(function () {
     $(".pop").fadeOut(600);
 });
 });


;(function($) {
$.fn.unveil = function(threshold, callback) {
var $w = $(window),
th = threshold || 0,
retina = window.devicePixelRatio > 1,
attrib = retina? "data-src-retina" : "data-src",
images = this,
loaded;
this.one("unveil", function() {
var source = this.getAttribute(attrib);
source = source || this.getAttribute("data-src");
if (source) {
this.setAttribute("src", source);
if (typeof callback === "function") callback.call(this);
}
});
function unveil() {
var inview = images.filter(function() {
var $e = $(this);
if ($e.is(":hidden")) return;
var wt = $w.scrollTop(),
wb = wt + $w.height(),
et = $e.offset().top,
eb = et + $e.height();
return eb >= wt - th && et <= wb + th;
});
loaded = inview.trigger("unveil");
images = images.not(loaded);
}
$w.on("scroll.unveil resize.unveil lookup.unveil", unveil);
unveil();
return this;
};
})(window.jQuery || window.Zepto);



/*      OWN JAVASCRIPT         */

$(document).ready(function() {
$("img").unveil(200, function() {
  $(this).load(function() {
    this.style.opacity = 1;
  });
});
});