栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python HTML解析,提供漂亮的汤和过滤停用词

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python HTML解析,提供漂亮的汤和过滤停用词

import urllib2import BeautifulSoupimport stringbadwords = set([    'cup','cups',    'clove','cloves',    'tsp','teaspoon','teaspoons',    'tbsp','tablespoon','tablespoons',    'minced'])def cleanIngred(s):    # remove leading and trailing whitespace    s = s.strip()    # remove numbers and punctuation in the string    s = s.strip(string.digits + string.punctuation)    # remove unwanted words    return ' '.join(word for word in s.split() if not word in badwords)def main():    url = "http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx"    data = urllib2.urlopen(url).read()    bs = BeautifulSoup.BeautifulSoup(data)    ingreds = bs.find('div', {'class': 'ingredients'})    ingreds = [cleanIngred(s.getText()) for s in ingreds.findAll('li')]    fname = 'PorkRecipe.txt'    with open(fname, 'w') as outf:        outf.write('n'.join(ingreds))if __name__=="__main__":    main()

结果是

olive oilchicken brothgarlic,paprikagarlic powderpoultry seasoningdried oreganodried basilthick cut boneless pork chopssalt and pepper to taste

?我不知道为什么它在其中留下了逗号-s.strip(string.punctuation)应该已经解决了。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号