【问题标题】:Python strp csv rows example .Show me how you would go about with thisPython strp csv rows example。告诉我你将如何处理这个
【发布时间】:2011-02-04 12:29:18
【问题描述】:

想象一下,如果您在 CSV 中有数千行这样的内容。

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

。

#! /usr/bin/env python
# Split the CSV and eliminate text before GET/ and text after HTTP1.1 and reorganize in simple sheet . 

import csv

try:
    dremel = csv.reader(open('dremel-columns.csv', 'rb'), delimiter=' ', quotechar='|')

except IOError:
    print 'CSV Error'


dremel_list= list(dremel)
dremel_l = []
cw = csv.writer(open("out.txt", "wb"))

#print dremel_list

for l in dremel_list:
    if l[1:-1]:
        l_shout = l[1:-1]
        #print l_shout
        cw.writerow(l_shout)
        #print "".join(l_shout)

        #cw.writerow("".join(l_shout)) 

【问题讨论】:

  • 只是一个头脑练习 - 每天至少练习一次想象一些特定的事情!
  • 我想我会问任何雇用我的人,他们想让我用这样的 csv 做什么,有数千行。
  • 这是Qn?拆分 CSV 文件行并消除 GET/ 之前的文本和 HTTP1.1 之后的文本并在简单的工作表中重新组织。告诉我你的代码版本,你将如何处理这个..

标签: python algorithm csv


【解决方案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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多