Python re.findall输出到CSV只能工作

时间:2017-09-21 17:51:18

标签: python regex export-to-csv

有一些代码可以在字符串中找到一些匹配的术语,在我的例子中是一个日志文件,我试图将实例输出到有效的csv,但有时只是。如果我有太多变量,它似乎打破并输出一个空白的csv,否则它实际上是有效的。

作品:

 z = re.findall("(?<=ID\=)\w+", resp)
rec = re.findall("(?<=RECEIVED\=)\w+", resp)

with open('/out.csv','w') as file:
    for x,y in zip(z,rec):
        file.write(x + ',' +y)
        file.write('\n')

给我一​​个空白的csv:

i = re.findall("(?<=ID\=)\w+", resp)
rec = re.findall("(?<=RECEIVED\=)\w+", resp)
da = re.findall("(?<=DA\=)\w+", resp)
oa = re.findall("(?<=OA\=)\w+", resp)
st = re.findall("(?<=DELIVERED\=)\w+", resp)
pr = re.findall("(?<=PRICE\=)\w+", resp)
net = re.findall("(?<=NETWORK\=)\w+", resp)
cn = re.findall("(?<=COUNTRY\=)\w+", resp)
gw = re.findall("(?<=GATEWAY\=)\w+", resp)
msg = re.findall("(?<=MSG\=)\w+", resp)

file = (i + ',' + rec + ',' + da + ',' + oa + ',' + st + ',' + pr + ',' + net + ',' + cn + ',' + gw + ',' + msg)
with open('out.csv','w') as file:
    for a,b,c,d,e,f,g,h,j,k in zip(i,rec,da,oa,st,pr,net,cn,gw,msg):
        file.write(a + ',' + b + ',' + c + ',' + d + ',' + e + ',' + f + ',' + g + ',' + h + ',' + j + ',' + k)
        file.write('\n')

也许我在想这个或做错了。基本上希望输出为这些输出为csv格式。如果我愚蠢,请随意嘘我。

1 个答案:

答案 0 :(得分:1)

使用pandas include函数pd.to_csv(...)并将信息存储在DataFrame中会不会更容易?

  

将DataFrame写入逗号分隔值(csv)文件。看到   Pandas

类似的东西:

i = re.findall("(?<=ID\=)\w+", resp)
rec = re.findall("(?<=RECEIVED\=)\w+", resp)
da = re.findall("(?<=DA\=)\w+", resp)
oa = re.findall("(?<=OA\=)\w+", resp)
st = re.findall("(?<=DELIVERED\=)\w+", resp)
pr = re.findall("(?<=PRICE\=)\w+", resp)
net = re.findall("(?<=NETWORK\=)\w+", resp)
cn = re.findall("(?<=COUNTRY\=)\w+", resp)
gw = re.findall("(?<=GATEWAY\=)\w+", resp)
msg = re.findall("(?<=MSG\=)\w+", resp)

indices = ("i", "rec", "da", "oa", "st", "pr", "net", "cn", "gw", "msg")

data = pd.DataFrame(data=zip(i, rec, da, oa, st, pr, net, cn, gw, msg), index=indices)
pd.DataFrame.to_csv(data, "out.csv")

@JSimonsen: 让我们看看这是否可以解决问题?

i = ['one', 'two']
rec = ['three', 'four']
da = ['five', 'six']
oa = ['seven', 'eight']

indices = ["col1", "col2"]

df = pd.DataFrame(data=zip(i, rec, da, oa), index=indices)
df.to_csv('out.csv')

由于我没有您正在使用的数据,这只是我可以尝试的一个简单示例,但re.findall()会返回strings的列表。所以它应该有用......