Search for list of keywords in python

大城市里の小女人 提交于 2019-12-12 04:54:27

问题


I've been able to search for keywords in strings before, but I'm running into a problem with using a list to do so. I keep getting this error.

TypeError: 'in <string>' requires string as left operand, not bool

I've tried every solution I could think of, but this is where I'm at right now:

from BeautifulSoup import BeautifulSoup
import urllib2

keywords = ['diy','decorate', 'craft', 'home decor', 'food']

def get_tags(blog_soup):
    tags_html = blog_soup.find('div', attrs = {'style': 'margin-left: 60px; margin-bottom: 15px;'})
    tags = [tag.string for tag in tags_html.findAll('a')]
    string_tags = str(' '.join(tags))
    if any(keywords) in string_tags:
        print url

url = 'http://technorati.com/blogs/blog.mjtrim.com'
soup = BeautifulSoup(urllib2.urlopen(url).read())

get_tags(soup)

回答1:


For a minimal change to get this working, you can change any(keywords) in string_tags to the following:

any(keyword in string_tags for keyword in keywords)

Or an alternative using sets:

keywords = set(['diy','decorate', 'craft', 'home decor', 'food'])

def get_tags(blog_soup):
    tags_html = blog_soup.find('div', attrs = {'style': 'margin-left: 60px; margin-bottom: 15px;'})
    tags = [tag.string for tag in tags_html.findAll('a')]
    if keywords.intersection(tags):
        print url


来源:https://stackoverflow.com/questions/18621403/search-for-list-of-keywords-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!