2013-10-23 14 views
5

Sto provando a spostare parte del mio lavoro di elaborazione da R a Python. In R, uso read.table() per leggere file CSV REALMENTE disordinati e divide automaticamente i record nel formato corretto. Per esempio.L'equivalente read.table di R in Python

391788,"HP Deskjet 3050 scanner always seems to break","<p>I'm running a Windows 7 64 blah blah blah........ake this work permanently?</p> 

<p>Update: It might have something to do with my computer. It seems to work much better on another computer, windows 7 laptop. Not sure exactly what the deal is, but I'm still looking into it...</p> 
","windows-7 printer hp" 

è correttamente separato in 4 colonne. 1 record può essere suddiviso su più righe e ci sono virgole dappertutto. In R Io faccio solo:

read.table(infile, header = FALSE, nrows=chunksize, sep=",", stringsAsFactors=FALSE) 

C'è qualcosa in Python che può fare questo altrettanto bene?

Grazie!

risposta

3

È possibile utilizzare il modulo csv.

from csv import reader 
csv_reader = reader(open("C:/text.txt","r"), quotechar="\"") 

for row in csv_reader: 
    print row 

['391788', 'HP Deskjet 3050 scanner always seems to break', "<p>I'm running a Windows 7 64 blah blah blah........ake this work permanently?</p>\n\n<p>Update: It might have something to do with my computer. It seems to work much better on another computer, windows 7 laptop. Not sure exactly what the deal is, but I'm still looking into it...</p>\n", 'windows-7 printer hp'] 

lunghezza di uscita = 4

+0

Ma questo restituisce solo stringhe. Non deduce il tipo di ciascuna colonna come fa read.table. –

2

Il modulo pandas ottime funzioni R-simili e strutture di dati, inclusi read_csv. Il vantaggio qui è che i dati verranno letti come un panda DataFrame, che è un po 'più facile da manipolare rispetto a una lista python standard o dict (specialmente se sei abituato a R). Ecco un esempio:

>>> from pandas import read_csv 
>>> ugly = read_csv("ugly.csv",header=None) 
>>> ugly 
     0            1 \ 
0 391788 HP Deskjet 3050 scanner always seems to break 

                2      3 
0 <p>I'm running a Windows 7 64 blah blah blah..... windows-7 printer hp