在python中处理unicode字符串

时间:2019-04-13 13:14:49

标签: python python-unicode unicode-escapes

我正在使用基于英语维基百科的快速文本预训练模型。它按预期工作...

https://github.com/shantanuo/pandas_examples/blob/master/nlp/fasttext_english.ipynb

但是当我用其他语言尝试相同的代码时,出现此页面上显示的错误...

https://github.com/shantanuo/pandas_examples/blob/master/nlp/fasttext_marathi.ipynb

该错误与unicode有关:

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

我尝试使用Raw Binary选项打开文件。我更改了load.py文件中的函数load_words_raw:

with open(file_path, 'rb') as f:

现在我得到了另一个错误:

  

ValueError:无法将字符串转换为浮点型:b'\ x00l \ x02'

我不知道该如何处理。

3 个答案:

答案 0 :(得分:1)

第15位的字节0x80 。文件可能会以UTF-16编码。 试试这个:

with open(path, encoding='utf-16') as f:
   // your logic   

答案 1 :(得分:1)

您应该将笔记本文件的第二行更改为:

#!wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.mr.300.vec.gz

因此指向vec文件,而不是bin文件:

#!wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.mr.300.bin.gz

答案 2 :(得分:0)

尝试一下:

data : str
with open('crawl-D.txt' ,'r', encoding='utf8') as file:
    data = file.read()

str将包含整个文件,名称为string

float解析float()