2014-06-16 77 views
1

我用python解析一个300页的文档,我需要找出ThisVal元素后的Response元素的属性值。有多个点,其中Response元素用于differentVals,所以我需要在找到ThisVal元素后找出Responseelements属性值中的内容。用标签解析Python文本文件

如果有帮助,令牌对于ThisVal是唯一的,但在每个文档中都不相同。

11:44:49 <ThisVal Token="5" /> 
11:44:49 <Response Token="5" Code="123123" elements="x.one,x.two,x.three,x.four,x.five,x.six,x.seven" /> 
+0

删除时间戳(例如使用'awk')并使用http://www.crummy.com/software/BeautifulSoup/bs4/doc/进行尝试。 –

+0

谢谢,这是有帮助的,但问题是在“thisval”后面找到它有100个响应标签,但我需要一个匹配特定元素的IE“thisval” – user2569803

回答

1

您是否考虑过使用pyparsing?我发现它对这种事情非常有用。以下是我对解决您的问题的尝试。

import pyparsing as pp 

document = """11:44:49 <ThisVal Token="5" /> 
11:44:49 <Response Token="5" Code="123123" elements="x.one,x.two,x.three,x.four,x.five,x.six,x.seven" /> 
""" 

num = pp.Word(pp.nums) 
colon = ":" 

start = pp.Suppress("<") 
end = pp.Suppress("/>") 
eq = pp.Suppress("=") 

tag_name = pp.Word(pp.alphas)("tag_name") 

value = pp.QuotedString("\"") 

timestamp = pp.Suppress(num + colon + num + colon + num) 
other_attr = pp.Group(pp.Word(pp.alphas) + eq + value) 

tag = start + tag_name + pp.ZeroOrMore(other_attr)("attr") + end 

tag_line = timestamp + tag 

thisval_found = False 

for line in document.splitlines(): 

    result = tag_line.parseString(line) 
    print("Tag: {}\nAttributes: {}\n".format(result.tag_name, result.attr)) 

    if thisval_found and tag_name == "Response": 
     for a in result.attr: 
      if a[0] == "elements": 
       print("FOUND: {}".format(a[1])) 

    thisval_found = result.tag_name == "ThisVal"