2011-02-04 50 views
-1

想象一下,如果您在CSV中有成千上萬行這樣的行。Python strp csv rows示例。演示如何使用此操作

maps.google.co.ke GET /maps?f=q&source=s_q&hl=en&geocode=&q=Africa&aq=0&sll=1.845384,32.871094&sspn=18.498214,20.786133&ie=UTF8&hq=&hnear=Africa&ll=-8.783195,34.508523&spn=69.476093,83.144531&z=3&output=embed HTTP/1.1 1.29646542461634E+015 168722060 1606370688 ? ken 

​​
+3

有什麼問題? – payne 2011-02-04 12:33:15

回答

1

我覺得這段代碼足以完成這項工作。

import re 

pat = re.compile('GET.*?HTTP1.1') 

with open('dremel-columns.csv', 'rb') as f_in, open("out.txt", "wb") as g_out: 
    g_out.write(u + '\n' for u in pat.finditer(f_in.read())) 

不是嗎?

編輯:對不起,我忘了 '\ n'

編輯2:不,它不會做

g_out.write(u for u in pat.finditer(f_in.read())) 
TypeError: must be string or buffer, not generator 

這一個工程

import re 

pat = re.compile('GET.*?HTTP1.1') 

with open('dremel-columns.csv', 'rb') as f_in, open("out.txt", "wb") as g_out: 
    for u in pat.finditer(f_in.read()): 
     g_out.write(u) 

或者,如果該文件是大任務:

import re 

pat = re.compile('GET.*?HTTP1.1') 

with open('dremel-columns.txt', 'rb') as f_in, open("out.txt", "wb") as g_out: 
    for line in f_in: 
     g_out.write(pat.search(line).group())