将unicode更改为字符串中的重音

时间:2018-01-24 09:49:45

标签: python python-3.x unicode encoding utf-8

我的csv文件中包含一个字符串,其中包含字符串内的unicode,而另一列则使用UTF-8正确读取 这是第一行:

  

Col1 | COL2
  rénovationthermique| [“consommation \ u00e9nerg \ u00e9tique de b \ u00e2timents publics”]

如何修复第二列,以便将unicode转换为重音?

编辑:我正在阅读csv:

pd.read_csv('data.csv', delimiter=',', header=0 )

添加“encoding ='utf-8'”并没有太大改变

我用

保存csv
df.to_csv('data.csv', encoding='utf-8', index=False)

并用

打印
print(df[0:2]) or directly df

2 个答案:

答案 0 :(得分:1)

Col2看起来像一个JSON格式的列表。不确定这是否是您所需要的,但以下内容将重新编写显示的input.csv作为output.csv。该代码假定input.csv以UTF-8编码。

<强> input.csv

Col1|Col2
rénovation thermique|["consommation \u00e9nerg\u00e9tique de b\u00e2timents publics"]

<强> rewrite.py

import csv
import json

with open('input.csv','r',newline='',encoding='utf8') as inf, \
     open('output.csv','w',newline='',encoding='utf8') as outf:

    r = csv.reader(inf,delimiter='|')
    w = csv.writer(outf,delimiter='|')

    header = next(r)
    w.writerow(header)

    for col1,col2 in r:
        newcol = json.loads(col2)    # Converts JSON to a list
        w.writerow([col1,newcol[0]]) # Replaces col2 with the list element.

<强> output.csv

Col1|Col2
rénovation thermique|consommation énergétique de bâtiments publics

答案 1 :(得分:0)

\u00e9 é (LATIN SMALL LETTER E WITH ACUTE)。 Python正确读取和处理该文件。

当您在其上使用\u00e9时,您的控制台上的此字符由print表示。如果您的控制台能够打印é,您会看到您的期望。

在我的系统上,此代码

s = "é"
print(s)
print(type(s))
print(len(s))

t = "\u00e9"
print(t)
print(type(t))
print(len(t))

打印

é
<class 'str'>
1
é
<class 'str'>
1

这正是我所期待的。

相关问题