2011-11-27 120 views
2

我的文本文件的行如下。这种类型的行在文件中多次出现。需要从Python的括号内的文本文件中读取数据

[年11月22 22点27分13秒] INFO - [com.macys.seo.business.impl.LinkBusinessImpl] - 执行搜索(WS)网关请求:KeywordVO(关键字= GUESS得分= 83965 normalizedKeyword = GUESS productIds = [] categoryIds = [] hotListed =假列入黑名单=假globalHotList =假URL = /购买/猜测)

我想仅在以下数据中提取到一个文件,如:

关键字=猜测,分数= 83965,hotListed = false,globalHotList = false url =/buy/GUESS

这是我到目前为止有:

def get_sentences(filename): 
    with open('d:\log.log') as file_contents: 
     d1, d2 = '(', ')' # just example delimiters 
     for line in file_contents: 
      if d1 in line: 
       results = [] 
      elif d2 in line: 
       yield results 
      else: results.append(line) 
    print results 

请指教。

+0

解决方案是否必须是Python的?你坚持哪部分? – Johnsyweb

+0

我只需要使用python。我的代码段是def get_sentences(filename): with open('d:\ log.log')as file_contents: d1,d2 ='(',')'#只是示例分隔符 for file in file_contents: if D1在行: 结果= [] ELIF D2在行: 收效 其他: results.append(线) 打印效果 – newcane

回答

1

Regular expressions可以帮助做一个单次解析:

import re, pprint 

with open('d:\log.log') as f: 
    s = f.read() 
results = re.findall(r'KeywordVO \((.*?)\)', s) 
pprint.pprint(results) 

上述正则表达式使用KeywordVO识别哪个括号是有关(我猜你不想的(WS)部分匹配示例文本)。您可能需要仔细查看日志文件,确定提取所需数据的准确正则表达式。

一旦你有所有关键字对的长文本字符串,使用另一个正则表达式分裂键/值对:r'[A-Za-z]+\s*=\s*[A-Za-z\[\]\,]'。这个正则表达式很棘手,因为您想要在等号的右侧捕获复数值,但不希望意外捕获下一个键(不幸的是,键/值对没有用逗号或其他符号分隔。

与解析好运:-)

1

您可以使用正则表达式:

>>> re.findall(r'\w+ = \S+', the_text) 
['keyword = GUESS', 'score = 83965', 'normalizedKeyword = GUESS', 
'productIds = []', 'categoryIds = []', 'hotListed = false', 
'blackListed = false', 'globalHotList = false', 'url = /buy/GUESS'] 

然后你可以分割=抢你所需要的人。

类似的东西:

>>> data = re.findall(r'\w+ = \S+', the_text) 
>>> ok = ('keyword', 'score', 'hotListed', 'url') 
>>> [i for i in [i.split(' = ') for i in data] if i[0] in ok 
[['keyword', 'GUESS'], ['score', '83965'], ['hotListed', 'false'], ['url', '/buy/GUESS']] 
+0

我陷在使用正则表达式拆分抢所需的人,请大家帮忙 – newcane

+0

@Ryder我编辑了答案 – JBernardo

+0

import re,pprint with open('d:\ log.log')as f: s = f.read() results = re。findall(r'\ w + = \ S +',s')这将打印所有的键/值对,我只需要在ok中定义的内容 ok =('keyword','score','hotListed','url') [我为我[i.split('=')为我在结果]如果我[0]在确定] pprint.pprint(results) – newcane