2012-10-07 99 views
0

我試圖從csv文件中的數據中刪除重音符號。所以我使用remove_accents函數(見下文),但爲此我需要使用utf-8編碼我的csv文件。 但我得到了錯誤'encoding' is an invalid keyword argument for this function
我見過我可能不得不使用Python3,然後執行python3 ./myscript.py? 這是正確的做法嗎?或者還有另一種方法可以刪除重音但不必安裝python3? 任何幫助,將不勝感激如何使用Python(編碼參數)從字符串中刪除重音符號?

#!/usr/bin/env python 

import re 
import string 
import csv 
import unicodedata 

def remove_accents(data): 
    return ''.join(x for x in unicodedata.normalize('NFKD', data) if \ 
    unicodedata.category(x)[0] == 'L').lower() 


reader=csv.reader(open('infile.csv', 'r', encoding='utf-8'), delimiter='\t') 
writer=csv.writer(open('outfile.csv', 'w', encoding='utf-8'), delimiter=',') 

for line in reader: 
    if line[0] != '': 
     person=re.split(' ',line[0]) 

     first_name = person[0].strip().upper() 
     first_name1=unicode(first_name) 
     first_name2=remove_accents(first_name1) 
     if len(person) == 2: 
      last_name=person[1].strip().upper() 
      line[0]=last_name 
     line[15]=first_name2 

    writer.writerow(line) 
+0

似乎是重複http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unico –

回答

1

您需要使用codecs.open()如果你希望能夠指定一個編碼。另外,unidecode

+0

(謝謝你的回答)我現在出現以下錯誤:UnicodeEncodeError:'ascii'編解碼器無法在位置24中編碼字符u'\ xa0':序號不在範圍內(128) – Reveclair

+0

http://farmdev.com/talks/unicode/ –

相關問題