python 从文本中提取每一行的特定字符串输出到csv文件

2024-11-09 10:14:05
推荐回答(2个)
回答1:

假设 你的文件名叫t.txt在当前目录下,

输出的CSV叫csv.txt也在当前目录

代码如下

import sys
import re
import csv 
pattern=r'.*(numberlocation)/\.(NumberLocationActivity).*\+(.*)ms'
cs=open('./csv.txt','w')
csvw=csv.writer(cs)

f=open('./t.txt')
for line in f:
 m=re.match(pattern,line)
 csvw.writerow(m.group(1,2,3))                                                                                                                              
f.close()
cs.close()

回答2:

#!/usr/bin/python
# coding: utf-8
#
# filename: regexTester.py
# author: Tim Wang
# date: Dec., 2013

import re

context = """12-06 14:50:23.600: I/ActivityManager(605): Displayed com.suning.numberlocation/.NumberLocationActivity: +125ms
12-06 14:50:52.581: I/ActivityManager(605): Displayed com.suning.numberlocation/.NumberLocationActivity: +126ms
12-06 14:51:21.391: I/ActivityManager(605): Displayed com.suning.numberlocation/.NumberLocationActivity: +108ms
12-06 14:51:50.652: I/ActivityManager(605): Displayed com.suning.numberlocation/.NumberLocationActivity: +121ms"""


patt = re.compile(r"""
    (?P
\d{1,2}-\d{2}\s\d{1,2}:\d{2}:\d{2}\.\d{3})
    .*
    (?<=NumberLocationActivity:\s\+)(?P\d+)ms
    """, re.I|re.U|re.X)

outputfmt = "numberlocation     NumberLocationActivity   %(numberlocation)s"
for ln in context.splitlines():
    print outputfmt % patt.match(ln).groupdict()