如何“清理”feedparser Feed中的所有条目

时间:2011-06-29 18:58:10

标签: python feedparser

我以Google的XML格式备份了我的博客。这很长。到目前为止,我已经这样做了:

>>> import feedparser
>>> blogxml = feedparser.parse('blog.xml')
>>> type(blogxml)
<class 'feedparser.FeedParserDict'>

在我正在阅读的书中,作者这样做:

>>> import feedparser
>>> llog = feedparser.parse("http://languagelog.ldc.upenn.edu/nll/?feed=atom")
>>> llog['feed']['title'] u'Language Log'
>>> len(llog.entries) 15
>>> post = llog.entries[2]
>>> post.title u"He's My BF"
>>> content = post.content[0].value
>>> content[:70] u'<p>Today I was chatting with three of our visiting graduate students f'
>>> nltk.word_tokenize(nltk.html_clean(content))

这对我来说是逐项的。如您所见,我已经有了一种使用NLTK清理HTML的方法。但我真正想要的是获取所有条目,清除HTML(我已经知道该怎么做,我不知道该怎么做,请更仔细地阅读这个问题),并将它们写成文件作为明文字符串。这与正确使用feedparser有关。有没有一种简单的方法可以做到这一点?

更新

事实证明,我仍然没有找到一种简单的方法来做到这一点。由于我对python的无能,我被迫做了一些有点丑陋的事情。

这就是我以为我会做的事情:

import feedparser
import nltk

blog = feedparser.parse('myblog.xml')

with open('myblog','w') as outfile:
    for itemnumber in range(0, len(blog.entries)):
        conts = blog.entries[itemnumber].content
        cleanconts = nltk.word_tokenize(nltk.html_clean(conts))
        outfile.write(cleanconts)

所以,非常感谢@Rob Cowie,但你的版本(看起来很棒)不起作用。我之前没有指出这一点并且接受答案我感到很难过,但我没有太多时间来处理这个项目。我放在下面的东西是我可以开始工作的,但是我打开这个问题以防有人有更优雅的东西。

import feedparser
import sys

blog = feedparser.parse('myblog.xml')
sys.stdout = open('blog','w')

for itemnumber in range(0, len(blog.entries)):
    print blog.entries[itemnumber].content

sys.stdout.close()

然后我CTRL-D'ed出了解释器,因为我不知道如何在不关闭Python的stdout的情况下关闭打开的文件。然后我重新进入解释器,打开文件,读取文件,并从那里清除HTML。 (nltk.html_clean是NLTK本书在线版本中的一个错字,顺便说一下......实际上是nltk.clean_html)。我最终得到的几乎是,但不完全是明文。

2 个答案:

答案 0 :(得分:1)

import feedparser
llog = feedparser.parse("http://languagelog.ldc.upenn.edu/nll/?feed=atom")

with open('myblog.txt', 'w') as outfile:
    for entry in llog.entries:
        ## Do your processing here
        content = entry.content[0].value
        clean_content = nltk.word_tokenize(nltk.html_clean(content))
        outfile.write(clean_content)

从根本上说,您需要打开一个文件,迭代条目(feed.entries),根据需要处理条目并将相应的表示写入文件。

我没有假设你想如何界定文本文件中的帖子内容。此代码段也不会将帖子标题或任何元数据写入文件。

答案 1 :(得分:0)

相关问题