2017-10-07 52 views
0

我想解析HTML,获取文本,并返回每个单词(或潜在的每个文本片段)附带的标签列表。 例如,给定这个HTML:Python用标签列表解析HTML返回单词

<em>Blah blah blah</em> blah again <i>and then again</i> 

这将返回类似:

(("Blah", "em"), 
("blah", "em"), 
("blah", "em"), 
("blah", ""), 
("again", ""), 
("and", "i"), 
("then", "i"), 
("again", "i")) 

或:

(("Blah blah blah", "em"), 
    ("blah again", ""), 
    ("and then again", "i")) 

是否有工具或一个简单的方法来做到这一点?

感谢

回答

0

您可以使用此https://scrapy.org/

例如

<div class="quote"> 
    <span class="text">“The world as we have created it is a process of our 
    thinking. It cannot be changed without changing our thinking.”</span> 
    <span> 
     by <small class="author">Albert Einstein</small> 
     <a href="/author/Albert-Einstein">(about)</a> 
    </span> 
    <div class="tags"> 
     Tags: 
     <a class="tag" href="/tag/change/page/1/">change</a> 
     <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a> 
     <a class="tag" href="/tag/thinking/page/1/">thinking</a> 
     <a class="tag" href="/tag/world/page/1/">world</a> 
    </div> 
</div> 

你可以做这样的事情

>>> title = quote.css("span.text::text").extract_first() 
>>> title 
'“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”' 
>>> author = quote.css("small.author::text").extract_first() 
>>> author 
'Albert Einstein' 
+0

我不确定这会有所帮助。我想将这些单词与造型标签一起提取出来。 –

0

您可以创建一个循环使用的标签栈当你到达某个标签时,将它推到堆栈上普通单词将堆栈中的最后一项和该单词添加到您的列表中作为元组。如果列表为空,则当您到达结束标记时,将空字符串而不是标签用于元组,以便弹出堆栈中的最后一项。 (按堆栈我的意思是在python列表中,只是使用push和pop函数来添加和删除项目)

+0

这就是我的想法,我只是希望这样的事情已经存在。 –

+0

有可能是一个html解析器,但它可能会给你一个不同的数据结构作为输出(可能是一棵树) – user8552411

+0

这并没有提供一个问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供无需澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an -i-do-instead) - [来自评论](https://stackoverflow.com/review/first-posts/17657789) – Sand