在做到集体智慧编程第三章开始(对订阅源中的单词进行计数)就卡住,出现错误是
object has no attribute 'title'
源代码是
#encoding=utf-8
import feedparser
import re
import jieba
#返回一个RSS订阅源
def getwordcounts(url):
d=feedparser.parse(url)
wc={}
#循环遍历所有的文章条目
for e in d.entries:
if 'summary' in e:summary=e.summary
else:summary=e.description
#提取一个单词列表
words=getwords(e.title+' '+summary)
for word in words:
wc.setdefault(word,0)
wc[word]+=1
#百度getattr(类,对象,默认),如果有对象就输出对象值,没有对象就将默认值赋值给对象,并输出该对象
return d.feed.title,wc
def getwords(html):
#除去所有HTML标记
txt=re.compile(r'<[^>]+>').sub('',html)
#re.compile(pattern[, flags])作用:把正则表达式语法转化成正则表达式对象。r是raw(原始)的意思。因为在表示字符串中有一些转义符,如表示回车'\n'。如果要表示\表需要写为'\\'。但如果我就是需要表示一个'\'+'n',不用r方式要写为:'\\n'。但使用r方式则为r'\n'这样清晰多了。
#re.sub(pattern, repl, string, count=0, flags=0)
#利用所有的费字母字符拆分出单词
words=jieba.cut(txt,cut_all=True)
# words=re.compile(r'[^A-Z^a-z]+').split(txt)
#转化成小写形式
return [tok.lower() for tok in words if tok!='']
apcount={}
wordcounts={}
with open('feedlist.txt',encoding='utf-8') as f1:
for line in f1:
#try:
title,wc=getwordcounts(line)
wordcounts[title]=wc
for word,count in wc.items():
apcount.setdefault(word,0)
if count>1:
apcount[word]+=1
#except :
#print('faild ro parse feed %s'% line)
wordlist=[]
for w,bc in apcount.items():
frac=float(bc)/len(line)
if frac>0.1 and frac <0.5: wordlist.append(w)
with open('blogdata.txt','w',encoding='utf-8')as out:
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')
找了半天,发现http://lobert.iteye.com/blog/2028779兄弟帮我解决了中文摘要的问题,这个问题还是没有解决,他们只是用try except把错误给隐藏了。
我在
getwordcounts函数return前打印title,都能出来,这个异常真的好奇怪,接着把这个异常在网上找答案,终于在
寻找到http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed19fa950d100b96204a05d93e788090412189d65f93130a1c187ba0fc7063565f8e993d7a01a44b58e0f63c752a5066f1db93d80d9becc5686fd56723706adb114a8448e9dc46539b73d14de9d945baadf044c0e894938404148c04127af6b6d01c5e43de2aad5467ecf5df0e550440fdab6772fe292069df7e00a14689f7331d108086800c14947b967611e6f566f12912c44ff9081b5517e60af153016176b758278e533d7585ea2da1713f1e74&p=c67dc64ad4934eaf5be7cb604d499c&newp=857fc64ad4934eaf5be7c031564d9e231610db2151d4d11f6b82c825d7331b001c3bbfb423241b00d1cf7f6505ab4c58eaf33374310727a3dda5c91d9fb4c57479&user=baidu&fm=sc&query=attributeError%3Aobject+has+no+attribute+%27title%27&qid=8d568ab7000141a4&p1=1上面这片文章,突然间豁然开朗,
原来不是个连接都是有title,没有就直接错,他是用到了return getattr(d.feed, 'title', 'Unknown title'), wc,问题立马解决