如何“清理”feedparser中的所有条目
我把我的博客备份成了谷歌的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)。最后得到的结果几乎是纯文本,但还不是完全的。
1 个回答
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
),根据需要处理这些内容,并把处理后的结果写入文件中。
我不假设你想用什么方式来分隔文本文件中的帖子内容。这个代码片段也没有把帖子标题或者任何其他信息写入文件。