2013-10-23 7 views
5

Ich versuche, einige meiner Verarbeitungsarbeit von R nach Python zu verschieben. In R verwende ich read.table(), um wirklich unordentliche CSV-Dateien zu lesen, und es teilt automatisch die Datensätze im richtigen Format auf. Z.B.R read.table entspricht 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" 

ist korrekt in 4 Spalten getrennt. 1 Datensatz kann über viele Zeilen verteilt werden und es gibt Kommas überall. In R ich nur tun:

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

Gibt es etwas in Python, die das genauso gut tun können?

Danke!

Antwort

3

Sie können das CSV-Modul verwenden.

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'] 

Länge output = 4

+0

Aber das gibt nur Strings zurück. Es leitet den Typ jeder Spalte nicht so ab wie die read.table. –

2

pandas Das Modul bietet auch viele R-ähnliche Funktionen und Datenstrukturen, einschließlich read_csv. Der Vorteil hierbei ist, dass die Daten als Pandas DataFrame eingelesen werden, was ein wenig einfacher zu managen ist als eine Standard-Python-Liste oder ein Standard-Diktat (besonders wenn Sie an R gewöhnt sind). Hier ist ein Beispiel:

>>> 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