需要从Python括号内的文本文件中读取数据

2024-10-01 15:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的文本文件的行如下。这种类型的行在文件中多次出现。在

[Nov 22 22:27:13] INFO -[com.macys.seo.business.impl.LinkBusinessImpl]- Executing Search(WS) Gateway request : KeywordVO ( keyword = GUESS score = 83965 normalizedKeyword = GUESS productIds = [] categoryIds = [] hotListed = false blackListed = false globalHotList = false url = /buy/GUESS )

我只想将以下数据提取到文件中,例如:

keyword = Guess, Score = 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

请告知。在


Tags: 文件inlogfalseurllinecontentsbuy
2条回答

您可以使用regex:

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

然后,您可以拆分=并获取所需的。在

像这样:

^{pr2}$

Regular expressions可能有助于一次完成解析:

import re, pprint

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

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

一旦您有了所有关键字对的长文本字符串,请使用另一个正则表达式来拆分键/值对:r'[A-Za-z]+\s*=\s*[A-Za-z\[\]\,]'。此正则表达式很棘手,因为您希望捕获等号右侧的复杂值,但又不希望意外地捕获下一个键(不幸的是,键/值对没有用逗号之类的分隔。在

祝你的分析好运:-)

相关问题 更多 >

    热门问题