吉吉于

free

为聚类算法采集数据:统计博客单词频度

今天开始研究数据的聚类算法,首先准备一些数据,这里我们采集博客的RSS来获取单词使用计数。

示例:

这里使用了搜索引擎对关键字的收录量来比喻,其实也可以用博客来代替搜索引擎。

所以就可以根据单词出现的频度对博客进行分类,可以帮助我们分析出是否存在一类博客用户,这些人写一些相似的文章,相似的写作风格。

为了构造一个这样的数据集,我们需要一个博客RSS列表,从中提取文本,建立单词频度表。

为了解析RSS,我们需要使用Universal Feed Parer,可以轻松帮助我们获取标题,链接,文章条目等。

介绍:它是一个通用的分析RSS和ATOM的模块

Universal Feed Parser is a Python module for downloading and parsing syndicated feeds. It can handle RSS 0.90, Netscape RSS 0.91, Userland RSS 0.91, RSS 0.92, RSS 0.93, RSS 0.94, RSS 1.0, RSS 2.0, Atom, and CDF feeds.

下载地址:http://www.feedparser.org

示例:

import feedparser

d = feedparser.parse(‘http://feed.feedsky.com/Lazynight’)

d[‘feed’][‘title’] u’Lazynight’

OK,废话多了,下边写代码,一个从订阅源中提取所有单词:

import feedparser
import re

# Returns title and dictionary of word counts for an RSS feed
def getwordcounts(url):
  # Parse the feed
  d=feedparser.parse(url)
  wc={}

  # Loop over all the entries
  for e in d.entries:
    if 'summary' in e: summary=e.summary
    else: summary=e.description

    # Extract a list of words
    words=getwords(e.title+' '+summary)
    for word in words:
      wc.setdefault(word,0)
      wc[word]+=1
  return d.feed.title,wc

def getwords(html):
  # Remove all the HTML tags
  txt=re.compile(r'<[^>]+>').sub('',html)

  # Split words by all non-alpha characters
  words=re.compile(r'[^A-Z^a-z]+').split(txt)

  # Convert to lowercase
  return [word.lower() for word in words if word!='']

保存为feed.py运行如下:

reload(feed)

<module ‘feed’ from ‘feed.py’

feed.getwordcounts(‘http://feed.feedsky.com/Lazynight’) (u’Lazynight’, {u’beautiful’: 2, u’www’: 1, u’last’: 1, u’gr’: 1, u’movielens’: 2, u’python’: 2, u’icio’: 1, u’no’: 1, u’us’: 1, u’cd’: 1, u’soup’: 2, u’html’: 2, u’del’: 1, u’mp’: 1, u’delicious’: 1, u’http’: 1, u’fm’: 1})

好了,现在已经获取我个人博客的单词频度表,现在我们通过一个博客RSS列表来获取大量的单词频度统计。

列表地址:http://kiwitobes.com/clusters/feedlist.txt

现在加入以下代码,遍历feedlist.txt生成数据,并保存到blogdata.txt中

apcount={}
wordcounts={}
feedlist=[line for line in file('feedlist.txt')]
for feedurl in feedlist:
  try:
    title,wc=getwordcounts(feedurl)
    wordcounts[title]=wc
    for word,count in wc.items():
      apcount.setdefault(word,0)
      if count>1:
        apcount[word]+=1
  except:
    print 'Failed to parse feed %s' % feedurl

wordlist=[]
for w,bc in apcount.items():
  frac=float(bc)/len(feedlist)
  if frac>0.1 and frac<0.5:
    wordlist.append(w)

out=file('blogdata1.txt','w')
out.write('Blog')
for word in wordlist: out.write('\t%s' % word)
out.write('\n')
for blog,wc in wordcounts.items():
  print blog
  out.write(blog)
  for word in wordlist:
    if word in wc: out.write('\t%d' % wc[word])
    else: out.write('\t0')
  out.write('\n')

运行:

import feed

解析过程很慢而且有可能会提示错误,不过等几分钟就会生成blogdata.txt,里边有大量的单词频度记录

好了,这节是为下节做数据准备,下节正在酝酿~

 

转载请注明:于哲的博客 » 为聚类算法采集数据:统计博客单词频度