2017-07-14 60 views
-4

我想用_替换nonunicode字符,但是这个程序尽管编译没有错误,但不能解决问题,我无法确定原因。UnicodeError替换不工作 - Python

import csv 
import unicodedata 
import pandas as pd 

df = pd.read_csv('/Users/pabbott/Desktop/Unicode.csv', sep = ',', 
index_col=False, converters={'ClinetEMail':str, 'ClientZip':str, 
'LocationZip':str, 'LicenseeName': str, 'LocationState':str, 
'AppointmentType':str, 'ClientCity':str, 'ClientState':str}) 

data = df 
for row in data: 
    for val in row: 
     try: 
      val.encode("utf-8") 
     except UnicodeDecodeError: 
      replace(val,"_") 

data.to_csv('UnicodeExport.csv', sep=',', index=False, 
quoting=csv.QUOTE_NONNUMERIC) 
+0

什么是您会收到错误? – MattR

+0

发布代码转储不是问题。 –

+0

我没有收到任何错误,因为代码编译正确,但在新文件中,那些nonunicode字符没有被_正确替换。我想知道这是否是data.apply函数的问题? –

回答

0
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 4: invalid start byte 

上述消息(来自pd.read_csv抛出)示出了该文件未保存在utf-8。您需要

  • 要么将文件保存为utf-8
  • 读取使用正确编码的文件。

例如(后者的变体),加encoding='windows-1252'df = pd.read_csv(…如下:

df = pd.read_csv('/Users/pabbott/Desktop/Unicode.csv', sep = ',', encoding='windows-1252', 
index_col=False, converters={'ClinetEMail':str, 'ClientZip':str, 
'LocationZip':str, 'LicenseeName': str, 'LocationState':str, 
'AppointmentType':str, 'ClientCity':str, 'ClientState':str}) 

然后,您可以省略所有的东西 try: val.encode("utf-8") for row in data: for val in row:循环。

阅读pandas.read_csv

encoding : str , default None

Encoding to use for UTF when reading/writing (ex. 'utf-8'). List of Python standard encodings .