2017-09-25 9 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

sタグはpタグ内にあり、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

これはロットクリーナーです。ありがとう –

関連する問題