python - 如何 'clean' feedparser feed 中的所有条目

标签 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 退出解释器,因为我不知道如何在不关闭 Python 标准输出的情况下关闭打开的文件。然后我重新进入解释器,打开文件,读取文件,并从那里清理 HTML。 (nltk.html_clean是NLTK书本身在线版本中的一个拼写错误,顺便说一句......它实际上是nltk.clean_html)。我最终得到的几乎是纯文本,但不完全是纯文本。

最佳答案

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),根据需要处理条目并将适当的表示形式写入文件。

我不假设您希望如何在文本文件中分隔帖子内容。此代码段也不会将帖子标题或任何元数据写入文件。

关于python - 如何 'clean' feedparser feed 中的所有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6525783/

相关文章:

python - Holoviews 曲线中的关键维度用于在字典中查找值

python 值与引用

Ruby,为什么 FeedNormalizer 的使用会破坏 Classifier::CRM114

java - 是否可以在 Android 上使用 GoogleFinanceAPI?

python - 在 feedparser 中使用 ETag

python - 可选的多个返回值

python - 如何以编程方式将 lambda 监听器规则注册到 ALB?

python - 列表中的两个以下元素

python - feedparser 出现 UndeclaredNamespace 错误

python - 使用 feedparser 按日期限制 RSS 元素。 [Python]