python - 如何在 Python3 中将字符串转换为 unicode?
问题描述
我尝试了很多方法将字符串如 b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a' 转换为汉字但都失败了.
当我刚刚使用时真的很奇怪
打印(b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a')
它将显示解码的汉字。
但是如果我通过从我的 CSV 文件中读取字符串,它就不会这样做。无论我如何解码字符串,它只会显示 b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'
这是我的脚本:
import csv
with open('need_convert.csv','r+') as csvfile:
reader=csv.reader(csvfile)
for row in reader:
new_row=''.join(row)
print('new_row:')
print(type(new_row))
print(new_row)
print('convert:')
print(new_row.decode('utf-8'))
这是我的数据(csv 文件): b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a' b'\xef\xbb\xbf \xe9\xba\x92\xe9\xba\x9f\xe6\x9d\xaf'b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\ x8a'
解决方案
row
内容和new_row
都是字符串,而不是字节类型。exec('s=' + row[0])
下面,假设输入是安全的,我将根据需要来解释它们。
import csv
with open('need_convert.csv','r+') as csvfile:
reader=csv.reader(csvfile)
for row in reader:
print(type(row[0]), row[0])
exec('s=' + row[0])
print(type(s), s)
print(s.decode('utf-8'))
输出:
<class 'str'> b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'
<class 'bytes'> b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'
国际友谊
<class 'str'> b'\xef\xbb\xbf\xe9\xba\x92\xe9\xba\x9f\xe6\x9d\xaf'
<class 'bytes'> b'\xef\xbb\xbf\xe9\xba\x92\xe9\xba\x9f\xe6\x9d\xaf'
麒麟杯
<class 'str'> b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'
<class 'bytes'> b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'
国际友谊
推荐阅读
- java - JTextArea - 双击/三次单击+移动鼠标时的选择行为
- java - 读入双打返回零而不是实际值
- magento2 - 我可以在 magento2 中集成自定义 JavaScript 支付方式吗?
- android - Android PIE API 28 - 'SQLite:没有这样的表错误'
- python - 如何将图像从 RGB 域转换为 YST 域?
- mysql - 在 node,js 中等待 MySQL 查询执行
- apache-kafka-streams - 使用 RocksDB-Cloud 的 Kafka 流状态存储
- c# - 将 WPF 文本框长度调整为报告文本框中允许的最大字符数
- excel - 如何在vba的Range方法中连接列名?
- html - 将滚动条定位在屏幕底部,并对齐列