简体   繁体   English

使用 Python 在 url 列表中搜索特定单词列表

[英]Search for specific word list in a list of urls using Python

I'm trying to determine whether or not a list of URLs contain specific words.我正在尝试确定 URL 列表是否包含特定单词。 Below is my code:下面是我的代码:


url_list = ['website1.com', 'website2.com']

cci_words = ['Risk Management', 'Labor', 'Migrant Workers']

total_words = []
for url in url_list:
    r = requests.get(url, allow_redirects=False)
    soup = BeautifulSoup(r.content.lower(), 'lxml')
    words = soup.find_all(text=lambda text: text and cci_words.lower() in text)
    count = len(words)
    cci_words = [ ele.strip() for ele in words ]
    for word in words:
        total_words.append(word.strip())

    print('\nUrl: {}\ncontains {} of word: {}'.format(url, count, cci_words))
    print(cci_words)

#print(total_words)
total_count = len(total_words)

But I keep getting this error: AttributeError: 'list' object has no attribute 'lower'但我不断收到此错误: AttributeError: 'list' object has no attribute 'lower'

Any ideas what should I do??任何想法我该怎么办?

In your for loop you cast cci_words to a list in the below line, so your program is throwing an error after it iterates through the loop a second time and tries to call lower() on cci_words.在您的 for 循环中,您将 cci_words 转换为下一行中的列表,因此您的程序在第二次迭代循环并尝试在 cci_words 上调用 lower() 后抛出错误。

cci_words = [ ele.strip() for ele in words ]

You seem to be making this probem quite complex where you could do something like this if you want any word in the list being present to return True.您似乎使这个问题变得非常复杂,如果您希望列表中存在的任何单词返回 True,您可以执行类似的操作。

def words_in_url_list(words: List[str], url_list: List[str]) -> bool:
    count = 0
    for word in words:
        word = word.lower()
        [count += 1 for url in url_list if word in url]
    return count > 0

If you want to check for all the words in the list, you could try this approach.如果您想检查列表中的所有单词,您可以尝试这种方法。

def all_words_in_url_list(words: List[str], url_list: List[str]) -> bool:
    comparison: set[str] = set()
    for word in words:
        word = word.lower()
        [comparison.add(word) for url in url_list if word in url]
    return len(words) == len(comparison)
        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM