StringIO in Python3

后端 未结 8 1878
清酒与你
清酒与你 2020-11-22 13:33

I am using Python 3.2.1 and I can\'t import the StringIO module. I use io.StringIO and it works, but I can\'t use it with numpy\'s

8条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 14:32

    Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.

    Python 2.7

    See: 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)
    """
    
    """
    
    print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
    """
    [['1' 'abc' '2']
     ['3' 'xxx' '4']]
    """
    
    print '\n', type(data)
    """
    
    """
    
    print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
    """
    [[  1.  nan   2.]
     [  3.  nan   4.]]
    """
    

    Python 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))
    """
    
    """
    
    #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.]]
    """
    

    Aside:

    dtype="|Sx", where x = any of { 1, 2, 3, ...}:

    dtypes. Difference between S1 and S2 in Python

    "The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ..."

提交回复
热议问题