2017-09-25 76 views
0

我想從YouTube視頻的字幕腳本中提取文本。我使用video.google.com獲取了XML文件。現在我想從xml文件中提取文本。我嘗試了以下,但我得到一個AttributeError: 'NoneType' object has no attribute 'text'錯誤。我只添加了一個xml文件的樣本,因爲它可能會變得太長。使用python解析XML時的屬性錯誤

from xml.etree import cElementTree as ET 
xmlstring = """<timedtext format="3"> 
<style type="text/css" id="night-mode-pro-style"/> 
<link type="text/css" rel="stylesheet" id="night-mode-pro-link"/> 
<head> 
<pen id="1" fc="#E5E5E5"/> 
<pen id="2" fc="#CCCCCC"/> 
<ws id="0"/> 
<ws id="1" mh="2" ju="0" sd="3"/> 
<wp id="0"/> 
<wp id="1" ap="6" ah="20" av="100" rc="2" cc="40"/> 
</head> 
<body> 
<w t="0" id="1" wp="1" ws="1"/> 
<p t="30" d="5010" w="1"> 
<s ac="252">in</s> 
<s t="569" ac="252">the</s> 
<s t="1080" ac="252">last</s> 
<s t="1260" ac="227">video</s> 
<s p="2" t="1500" ac="187">we</s> 
<s p="2" t="1860" ac="160">started</s> 
<s p="2" t="2190" ac="234">talking</s> 
</p> 
<p t="2570" d="2470" w="1" a="1"></p> 
<p t="2580" d="5100" w="1"> 
<s ac="252">about</s> 
<s t="59" ac="227">Markov</s> 
<s t="660" ac="252">models</s> 
<s p="1" t="1200" ac="217">as</s> 
<s t="1379" ac="252">a</s> 
<s t="1440" ac="252">way</s> 
<s t="1949" ac="252">to</s> 
<s t="2009" ac="252">model</s> 
</p> 
</body> 
</timedtext>""" 

words = [] 
root = ET.fromstring(xmlstring) 
for page in list(root): 
    words.append(page.find('s').text) 

text = ' '.join(words) 

視頻的文本是在<s>標籤,但我不能提取它們。任何想法該怎麼辦?在此先感謝

回答

2

在p標籤內找到s標籤,在身體標籤內找到p標籤。您可以稍微更改代碼。

words = [] 
root = ET.fromstring(xmlstring) 
body = root.find("body") 

for page in body.findall("p"): 
    for s in page.findall("s"): 
     words.append(s.text) 

text = ' '.join(words) 
+0

非常感謝Mitiku。 –

1

您可以循環s tag直接

root = ET.fromstring(xmlstring) 
words = [s.text for s in root.findall(".//s")] 
text = ' '.join(words) 
+0

嗯,這很乾淨。謝謝 –