遇到这种问题,就是文件编码的缘故。
最好的解决方式就是,以二进制的方式读,然后以正确的编码重新encode它。
示例:
#我想要utf-8格式的
with open('words.vec','rb') as f:
lines=[l.decode('utf8','ignore') for l in f.readlines()]
如果还是有乱码,可以这样玩:
import re
# 判断一个字符串是否是小数
def IsFloat(s):
pattern = '^-?\d+\.?\d*$' # 匹配数字: 从头开始匹配 -0或1次 数字1或多次 .0或1次 数字0或多次 匹配到字符串末尾
match = re.match(pattern, s)
return match != None
word_embeddings = {}
with open('words.vec','rb') as f:
lines=[l.decode('utf8','ignore') for l in f.readlines()]
lines=lines[1:]
for line in lines:
if len(line)<10:
break
data = line.strip().split()
name=str(data[0])
content=data[1:]
con=[]
for i in content:
if not IsFloat(i):
break
con.append(float(i))
word_embeddings[name] = con
print(len(word_embeddings))