2012-08-11 11 views
192

Sto usando Python 3.2.1 e non riesco a importare il modulo StringIO. Io uso io.StringIO e funziona, ma non posso usarlo con numpy s' genfromtxt come questo:StringIO in Python3

x="1 3\n 4.5 8"   
numpy.genfromtxt(io.StringIO(x)) 

ottengo il seguente errore:

TypeError: Can't convert 'bytes' object to str implicitly 

e quando scrivo import StringIO si dice

ImportError: No module named 'StringIO' 

risposta

50

Su Python 3 numpy.genfromtxt si aspetta un flusso di byte. Utilizzare la seguente:

numpy.genfromtxt(io.BytesIO(x.encode())) 
342

when i write import StringIO it says there is no such module.

Da What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

.


Procedimento eventualmente utile di fissazione codice Python 2 a lavorare anche in Python 3 (emptor di avvertimento):

try: 
    from StringIO import StringIO 
except ImportError: 
    from io import StringIO 

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the the message TypeError: Can't convert 'bytes' object to str implicitly , see this answer .

+6

Vale la pena menzionare questi non sono gli stessi, in modo da poter finire con 'TypeError's (argomento stringa previsto, ottenuto 'byte') se si effettua questa modifica in isolamento. È necessario distinguere attentamente btyes e str (unicode) in python 3. –

+5

Per i newb come me: da io import StringIO significa che lo si chiama come StringIO(), non io.StringIO(). – Noumenon

+4

Come effettivamente essere compatibile con Python 2 e 3: solo 'da io import StringIO' –

21

Nel mio caso ho utilizzato:

from io import StringIO 
11

Grazie OP per la tua domanda e Roman per la tua risposta. Ho dovuto cercare un po 'per trovare questo; Spero che quanto segue aiuti gli altri.

Python 2,7

See: https://docs.scipy.org/doc/numpy-dev/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.]] 
""" 

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

parte:

DTYPE = "| Sx", dove x = qualsiasi {1, 2, 3, ...}:

dtypes. Difference between S1 and S2 in Python

"L'| S1 e | S2 stringhe sono dati di tipo descrittori; Il primo mezzo della matrice contiene stringhe di lunghezza 1, il secondo di lunghezza 2. ..."

8

È possibile utilizzare il StringIO dal modulo six:

import six 
import numpy 

x = "1 3\n 4.5 8" 
numpy.genfromtxt(six.StringIO(x)) 
-5

provare questo

da StringIO import StringIO

x = "1 3 \ n 4.5 8"

numpy.genfromtxt (StringIO (x))

3

Al fine di rendere esempi da here lavoro con Python 3.5.2, è possibile riscrivere come segue:

import io 
data =io.BytesIO(b"1, 2, 3\n4, 5, 6") 
import numpy 
numpy.genfromtxt(data, delimiter=",") 

La ragione per il cambiamento può essere che il contenuto di un file è nei dati (byte), che non fanno testo finché non viene decodificato in qualche modo. genfrombytes può essere un nome migliore di genfromtxt.