简体   繁体   English

非ASCII字符'\\ xc5'破坏python脚本

[英]Non-ASCII character '\xc5' breaking python script

My node.js server outputs the following array: 我的node.js服务器输出以下数组:

["Daniel Guillen","Sarah Tremaine Milam","Karen Ann"...."Chris Doyle","Katie Gould"]

I'm trying to convert it to a csv file using a python script but when I declare the array in my .py file I get the following error: 我正在尝试使用python脚本将其转换为csv文件,但是当我在.py文件中声明数组时,出现以下错误:

SyntaxError: Non-ASCII character '\xc5' in file toCSV.py

The array consists of people's names from Facebook so someone somewhere has a weird character in their name. 该数组由来自Facebook的人的名字组成,因此某人的名字中有一个奇怪的字符。 It is too long to manually search. 手动搜索太长。

How do you recommend working around this problem or finding the offending character? 您如何建议解决此问题或找到令人反感的角色? Iterating through the array in javascript before handing to python is also an option. 也可以选择在使用python之前遍历javascript中的数组。

If the array is embedded in the python script then you may need to set the encoding at the start of the python file. 如果该数组嵌入在python脚本中,则可能需要在python文件的开头设置编码。 To do this add the following line before any code: 为此,在任何代码之前添加以下行:

# -*- coding: utf-8 -*-

This sets the source code encoding to UTF-8. 这会将源代码编码设置为UTF-8。

You can use codecs (you'll have to import it) to read utf8 (non-ascii) characters. 您可以使用编解码器(必须将其导入)来读取utf8(非ascii)字符。 Like so: 像这样:

csvfile = codecs.open(outputFileName+".csv", 'w+', 'utf8')

That would be for writing to an output file. 那将用于写入输出文件。 If you want to read in a file, just change the 'w+' to 'r'. 如果要读取文件,只需将“ w +”更改为“ r”。 For individual strings, you can also use the method "string".encode('utf8') This fixes the issue if it's being read from another file. 对于单个字符串,还可以使用方法“ string” .encode('utf8'),如果从另一个文件读取该问题,则可以解决此问题。 If you have it in the file you're running, you need to set the encoding by putting 如果您正在运行的文件中有此文件,则需要通过以下方式设置编码:

# -*- coding: utf-8 -*- 

at top of file 在文件顶部

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

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