使用Python为一列中文字符插入一列拼音

时间:2014-10-26 04:24:44

标签: python python-2.7 csv

我目前正在使用http://lxyu.github.io/pinyin/正常工作。

import pinyin

print pinyin.get(u'你好')

我得到'nihao'是正确的。

使用以下格式的CSV文件:

陈升
"Mon Mon"
草蜢
李宇春
...

然而,当我尝试这样做时:

with open('ChineseNames.csv','rb') as fin, open('output.csv','wb') as fout:
    reader = csv.reader(fin, delimiter=' ', quotechar='|')
    writer = csv.writer(fout)
    for line in reader:
        writer.writerow(pinyin.get(line))

我明白了:

Traceback (most recent call last):
  File "singerpinyin.py", line 12, in <module>
    writer.writerow(pinyin.get(line))
  File "/usr/local/lib/python2.7/dist-packages/pinyin/pinyin.py", line 30, in get
    s = compat.u(s)
  File "/usr/local/lib/python2.7/dist-packages/pinyin/compat.py", line 12, in u
    return unicode(s, "utf-8")
TypeError: coercing to Unicode: need string or buffer, list found

尝试:

writer.writerow(pinyin.get(u'line'))

会输出错误的信息:

l,i,n,e
l,i,n,e
l,i,n,e
...

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

解决: 它应该是pinyin.get(line [0])。