python解决numpy导入乱码问题------已解决

使用numpy的loadtxt时,发现报错,经历如下:

// Visual Studio Code
var foo = 'bar';
import numpy as np 

if __name__ == "__main__":
    dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt")  
    print(dataset)
 ········································································
 打印出的结果:
 ValueError: could not convert string to float: '1,1锛孉'

解决经历:
第一次:

// Visual Studio Code
var foo = 'bar';
import numpy as np 

if __name__ == "__main__":
    dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt",dtype="str")  #默认为float,需要dtype
    print(dataset)
···················································
打印出的结果:
['1,1锛孉' '1,2锛孉' '1.5,1.5锛孉' '3,4锛孊' '4,4锛孊']

第二次:

// Visual Studio Code
var foo = 'bar';
import numpy as np 

if __name__ == "__main__":
    dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt",dtype="str",encoding='utf-8')  #默认为float,需要dtype
    print(dataset)
打印出的结果:
['1,1,A' '1,2,A' '1.5,1.5,A' '3,4,B' '4,4,B']

优化后

// Visual Studio Code
var foo = 'bar';
import numpy as np 

if __name__ == "__main__":
    dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt",dtype="str",encoding='utf-8',delimiter=',')  #默认为float,需要dtype
    # x=dataset[:,:-1]    
    print(dataset)
打印的结果:
PS C:\Users\yanruyu> & D:/Anaconda3/python.exe c:/Users/yanruyu/Documents/code/python/GA/text.py
[['1' '1,A']
 ['1' '2,A']
 ['1.5' '1.5,A']
 ['3' '4,B']
 ['4' '4,B']]

你可能感兴趣的:(异常处理)