【问题标题】:Storing a list of unicode strings in a csv file python 2 [duplicate]在csv文件python 2中存储unicode字符串列表[重复]
【发布时间】:2018-04-29 19:04:05
【问题描述】:

我创建了一个返回如下列表的函数(parse_html(param)),

list = [u'John', u'Muchia', u'Prozessoptimierung Fahrwiderst\xe4nde']

如果我返回 print list[2],并且在我的函数中,它给了我 Prozessoptimierung Fahrwiderstände,这是完美的,但在列表中显示不同

问题在于当我返回整个列表return list 我想避免使用'u'。我想存储一个字符串列表,并且 ä ö 和 ü 等 Unicode 字符也应该出现。

fname[x] 是 HTML 文件的来源,其中 x 是文件编号,从 0 递增到 count(file_number)

list=[]
newlist=[]    
list = parse_html(fname[7])
for row in list:
  drow = row.encode('utf-8')
  newlist.append(drow)
print newlist

目标是将返回的列表保存到 CSV 文件中。每次选择新文件(fname)时,都会创建列表,并且应该将新列表添加到之前创建的 csv 文件中。

我做错了什么,我可以意识到这一点,我的头很痛。请帮忙。

更新:

for x in range(0,count):
    list = parse_html(fname[x])
    with open('output.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(list)

错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 132: ordinal not in range(1
28)

答案:

wr.writerow([c.encode('utf-8') for c in list]) # instead `wr.writerow(list)

【问题讨论】:

  • 你没有做错任何事,也不需要删除u。你为什么认为你会这样做?
  • 嗨丹尼尔,我的目标是将其保存在 csv 中。我更新了帖子,我认为你正在产生问题
  • 查看 python 中的 pandas 库,这很好处理
  • @jorzylicious:您唯一的问题是 Python 2 csv 库不擅长处理 Unicode。查看副本。
  • 不! Why sys.sysdefaultencoding will break code。改为学习正确使用 Unicode。

标签: python list csv unicode


【解决方案1】:

u 前缀仅表示字符串是 Unicode 格式。您的代码没有任何问题,它会在代码中正常运行(就好像它没有u)。它只是在 print 函数中输出,让您知道它是一个 Unicode 字符串。

【讨论】:

    【解决方案2】:

    问题出在您的 CSV 输出代码中。由于您使用的是 Python 2,因此您应该在编写之前直接编码为 utf-8:

        wr.writerow([c.encode('utf-8') for c in list])
    

    或者,升级到 Python 3 以获得更多集成的 unicode 支持。

    【讨论】:

    • UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 30: ordinal not in range(128)
    • 我包括 import sys reload(sys) sys.setdefaultencoding('utf-8') 它给出了一个 csv 输出 wr.writerow([c.decode('utf-8') for c in list ]) 感谢丹尼尔的帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 2012-05-03
    • 2017-04-03
    • 2017-03-15
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多