集体智慧编程第三章 发现群组

对订阅源中的单词进行计数
#!/usr/bin/python
#-*-coding:utf-8 -*-
import feedparser
import  re
#返回一个Rss 订阅源的标题和包含单词计数情况的字典
def getwordCounts(url):
    #解析订阅源:
    d=feedparser.parse(url)
    # print(d)
    wc={}
    #循环遍历所有的文章条目
    for e in d.entries:
        # print(e)
        if "summary" in e :
            summary=e.summary
        else :
            summary=e.description
        #提取一个单词列表  ?title中没有得到值
        # print("title:----   "+e.title+"   summary:----   "+summary)
        words=getwords(e.title+" "+summary)
        print("after:   "+str(words))
        for word in words:
             # print("each words in  ----"+word)
             wc.setdefault(word,0)
             wc[word]+=1
    return d.feed.title,wc

def getwords(html):
    print("enter getWords(Html)")
    #去除所有HTML 标记  compile(r'[^>]+>') 先对匹配模式进行编译,在匹配sub("",html)
    #  [^>]+ 不是>的字符重复一次到多次
    txt=re.compile(r'<[^>]+>').sub("",html)
    #利用所有非字母字符查分出单词
    words=re.compile(r"[^A-Z^a-z]+").split(txt)
    #转化为小写形似
    print(word.lower() for word in words if word!="")
    return [word.lower() for word in words if word!=""]

#利用上述单词列表和博客列表来建立一个文本文件(记录针对每个博客的所有单词的统计情况

apcount={}  #出现这些单词博客的数目
wordCounts={}  #所有博客的单词统计
#遍历文件中的每一行
feedlist=[lines for lines in open("feedlist.txt")]
for feed in feedlist:
#生成每个博客的单词统计
   try:
    title,wc=getwordCounts(feed)
    print(feed)
    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" % feed)

#计算某个单词出现的比例( 该单词在所有博客中出现的次数 /总博客,比值在 10% ----50%之间)
wordlist=[]
for word,count in apcount.items():
    level=count/len(feedlist)
    if level >=0.1  and level<0.5:
        wordlist.append(word)
    print(str(wordlist)+"-----wordlist")

#利用 单词列表和 博客列表建立一个文本文件,其中包含一个大的矩阵,记录着针对每个博客的所有单词的统计情况
# 把单词表和 在某个博客中他们各自出现的次数
out=file("blogdata.txt","w")
out.write("Blog")
for word in wordlist:
    out.write("\t%s"%word)
out.write("\n")
for blog,wc in wordCounts.items():
    out.write(blog)
    for word in wordlist:
        if word in wc:
            out.write("\t%d"% wc[word])
        else:
            out.write("\t0")
    out.write("\n")




猜你喜欢

转载自blog.csdn.net/qq_18617299/article/details/78755775