原始代码:
file = open(r'C:\Users\pi\Desktop\2.txt')
d = loadtxt(file, dtype=str)
print(d[0])
["b'love'" "b'byte'" "b'you'"]
file = open(r'C:\Users\pi\Desktop\2.txt', 'rb')
d = loadtxt(file, dtype=str)
print(d)
["b'love'" "b'byte'" "b'you'"]
file = open(r'C:\Users\pi\Desktop\2.txt', 'r', encoding='utf-8')
d = loadtxt(file, dtype=str)
print(d)
["b'love'" "b'byte'" "b'you'"]
输出的值前面总会在字符串前面加上“b”,原因是np.loadtxt and np.genfromtxt operate in byte mode, which is the default string type in Python 2. But Python 3 uses unicode, and marks bytestrings with this b. numpy.loadtxt中也声明了:Note that generators should return byte strings for Python 3k.
如何去除这个“b”,只需使用下面这个代码:
np.loadtxt(filename, dtype=bytes).astype(str)
作者:Cameron
链接:https://www.zhihu.com/question/28690341/answer/164344688
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。