Python xml解析器问题

时间:2018-12-18 21:35:02

标签: python xml pandas

简单代码无法正常工作,正在寻求帮助。

df有44000行,

<chat>
 <messages>
 <chat-message>
 <timestamp>2017-08-22T15:08:35.906-04:00</timestamp> 
  <name /> 
  <body>Hello Mikey, I see you want to chat with us today about: Account    
  Assistance. If you are chatting on a mobile device or tablet, your session 
  will end if you navigate away from the chat window. A representative will be 
  with you momentarily.</body> 
  <usertype>system</usertype> 
  </chat-message>
  <chat-message>

是具有自己标签的多个标签。我想抓住所有的身体部位并合并为一个条目。

def msgg(row):
    root = ET.fromstring(row)
    work = ""
    for body in root.findall('messages/chat-message/body'):
        work = work + body.text
        return work


for row in df5['chat']:
    try:
       df5['test'] = df5['chat'].apply(msgg)

    except:
        pass

我的函数有一个异常处理程序,因为没有它,我会收到此错误:

    ParseError: no element found: line 1, column 32759

互联网表示,当xml文件具有错误的标签时,会出现此错误。使用异常处理程序,我没有收到任何错误,但是代码花了很多时间才能运行。现在已经运行了35分钟;我敢肯定,当我最终获得结果时,它们将是垃圾。救命!

1 个答案:

答案 0 :(得分:0)

您的代码最有可能出现问题。这意味着您的数据集不干净,并且标签未正确关闭,例如

<name> stuff here <name /> 

应改为

<name> stuff here </name>

编辑:我创建了一个question来帮助解决字符串替换问题,以修复此格式错误的xml文档。希望这可以帮助您解决问题。

相关问题