gpt4 book ai didi

Python HTML 解析美汤和过滤停用词

转载 作者:行者123 更新时间:2023-11-27 22:48:25 26 4
gpt4 key购买 nike

我正在将网站上的特定信息解析到一个文件中。现在我的程序查看网页,找到正确的 HTML 标签并解析出正确的内容。现在我想进一步过滤这些“结果”。

例如,在网站上:http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx

我正在解析位于 < div class="ingredients"...> 标签中的成分。这个解析器很好地完成了这项工作,但我想进一步处理这些结果。

当我运行这个解析器时,它会删除数字、符号、逗号和斜杠(\或/),但保留所有文本。当我在网站上运行它时,我得到如下结果:

cup olive oil
cup chicken broth
cloves garlic minced
tablespoon paprika

现在我想进一步处理这个问题,删除诸如“cup”、“cloves”、“minced”、“tablesoon”等停用词。我该怎么做?这段代码是用 python 编写的,我不是很擅长,我只是使用这个解析器来获取我可以手动输入但我不想输入的信息。

任何有关如何详细执行此操作的帮助将不胜感激!我的代码如下:我该怎么做?

代码:

import urllib2
import BeautifulSoup

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 = [s.getText().strip('123456789.,/\ ') for s in ingreds.findAll('li')]

fname = 'PorkRecipe.txt'
with open(fname, 'w') as outf:
outf.write('\n'.join(ingreds))

if __name__=="__main__":
main()

最佳答案

import urllib2
import BeautifulSoup
import string

badwords = 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 oil
chicken broth
garlic,
paprika
garlic powder
poultry seasoning
dried oregano
dried basil
thick cut boneless pork chops
salt and pepper to taste

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

关于Python HTML 解析美汤和过滤停用词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com