我编写了一个简单的脚本,用于使用BeautifulSoup模块解析XML聊天日志。标准的soup.prettify()可以正常工作,只是聊天日志中有很多绒毛。您可以在下面看到脚本代码和我正在使用的一些XML输入文件:
码
import sys from BeautifulSoup import BeautifulSoup as Soup def parseLog(file): file = sys.argv[1] handler = open(file).read() soup = Soup(handler) print soup.prettify() if __name__ == "__main__": parseLog(sys.argv[1])
测试XML输入
<?xml version="1.0"?> <?xml-stylesheet type='text/xsl' href='MessageLog.xsl'?> <Log FirstSessionID="1" LastSessionID="2"><Message Date="10/31/2010" Time="3:43:48 PM" DateTime="2010-10-31T20:43:48.937Z" SessionID="1"><From><User FriendlyName="Jon"/></From> <To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, what's up?</Text></Message> <Message Date="10/31/2010" Time="3:44:03 PM" DateTime="2010-10-15T20:44:03.421Z" SessionID="1"><From><User FriendlyName="Jon"/></From><To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">Got your message</Text></Message> <Message Date="10/31/2010" Time="3:44:31 PM" DateTime="2010-10-15T20:44:31.390Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">oh, great</Text></Message> <Message Date="10/31/2010" Time="3:44:59 PM" DateTime="2010-10-15T20:44:59.281Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, i gotta run</Text></Message>
我希望能够将其输出为以下格式或至少比纯XML更可读的格式:
乔恩:嘿,怎么了?[10/31/10 @ 3:43p]
乔恩:收到了您的消息[10/31/10 @ 3:44p]
Bill:哦,太棒了[10/31/10 @ 3:44p]
等。我听说过有关PyParsing模块的一些体面的事,也许是时候试一试了。
BeautifulSoup使获取xml中的属性和值变得非常简单。我调整了示例功能以使用这些功能。
import sys from BeautifulSoup import BeautifulSoup as Soup def parseLog(file): file = sys.argv[1] handler = open(file).read() soup = Soup(handler) for message in soup.findAll('message'): msg_attrs = dict(message.attrs) f_user = message.find('from').user f_user_dict = dict(f_user.attrs) print "%s: %s [%s @ %s]" % (f_user_dict[u'friendlyname'], message.find('text').decodeContents(), msg_attrs[u'date'], msg_attrs[u'time']) if __name__ == "__main__": parseLog(sys.argv[1])