【问题标题】:regex results from a csv to a csv output从 csv 到 csv 输出的正则表达式结果
【发布时间】:2016-12-16 14:35:30
【问题描述】:

我想将我的结果保存在我的 csv 中。但不知何故,它仍然是空的。但是,如果我不在 csv 中写入相同的输出,而只在 print 中写入,我会得到我想要的结果。

import re
import glob
import os
## is the second script for matchParser.py, match the results for Duration in ms digit
lines = [line.strip() for line in open('output.csv')]
for result in lines:

    match = re.search(r'(!?\s.\d[Request completed in\s])', result)
    if match: print match.group(0)

但是这个带有 output_csv 的版本不工作,我不知道为什么..

import re
import glob
import os

lines = [line.strip() for line in open('output.csv')]
for result in lines:

    match = re.search(r'(!?\s.\d[Request completed in\s])', result)
    with open('outputREGEX5.csv', "w") as output_csv:
        if match: output_csv.write(match.group(0))

我也收到以下错误:

output.write(match.group(0))
AttributeError: 'NoneType' object has no attribute 'group'

感谢您的帮助。

-- 编辑 我的print 输出:

 44 
 37 
 53 
 35 
 17 
 35 
 25 
 27 
 50 
 31 
 27 
 36 
 17 
 66 
 46 
 41 
 38 
 23 
 33 

【问题讨论】:

    标签: python regex python-2.7 python-3.x csv


    【解决方案1】:
    open('outputREGEX5.csv', "w")
    

    清空文件。只在循环外打开文件一次,而不是每次迭代都打开它。

    with open('outputREGEX5.csv', "w") as output_csv:
        for result in lines:
            match = re.search(r'(!?\s.\d[Request completed in\s])', result)
            if match: output_csv.write(match.group(0) + '\n')
    

    【讨论】:

    • 你能不能更准确地解释一下,并确切地说我应该把它放在哪里?我是python的新手
    • 几乎...match = ... 行应该在if match: 之前,并且在相同的缩进级别。
    • 它的工作!但条目不像印刷版那样在换行符中。如何添加一个 \n 以便每次迭代都写入一个新行?
    • @harun 只需在您正在编写的内容中添加一个 \n 即可。来吧,试一试。
    • 我试过了。不幸的是没有成功。总是得到这个错误:NameError: name 'match' is not defined :/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多