Hướng dẫn dùng stringio python3 python

Cảm ơn OP vì câu hỏi của bạn và Roman cho câu trả lời của bạn. Tôi đã phải tìm kiếm một chút để tìm thấy điều này; Tôi hy vọng sau đây giúp đỡ người khác.

Python 2.7

Xem: https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html

import numpy as np
from StringIO import StringIO

data = "1, abc , 2\n 3, xxx, 4"

print type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
 ['3' 'xxx' '4']]
"""

print '\n', type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Con trăn 3.5:

import numpy as np
from io import StringIO
import io

data = "1, abc , 2\n 3, xxx, 4"
#print(data)
"""
1, abc , 2
 3, xxx, 4
"""

#print(type(data))
"""
<class 'str'>
"""

#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
 [b'3' b'xxx' b'4']]
"""

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Qua một bên:

dtype = "| Sx", trong đó x = bất kỳ {1, 2, 3, ...}:

bánh quy. Sự khác biệt giữa S1 và S2 trong Python

"Các chuỗi | S1 và | S2 là các mô tả kiểu dữ liệu; đầu tiên có nghĩa là mảng giữ các chuỗi có độ dài 1, thứ hai có độ dài 2. ..."

21 hữu ích 0 bình luận chia sẻ