2 回答

TA贡献1824条经验 获得超5个赞
for web_name, urls in medias.items():
for url in urls:
for word in words:
count = count_words(url, word)
print('La palabra {} aparece {} veces en el sitio del {}.'.format(word, count, web_name))
你传递了一个列表,而你应该传递一个词来count函数。

TA贡献1921条经验 获得超9个赞
我在您的代码中修复了一些错误:
首先,您在使用单词时忘记遍历数组,因此我在代码的最后添加了一个 for 循环来循环遍历这些单词。
其次,在我这样做之后,您的代码返回零,所以我将 .lower() 添加到 count_words 中的每个单词,然后它就起作用了。
import requests
import time
from bs4 import BeautifulSoup
headers = {
'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"}
def count_words(url, the_word):
r = requests.get(url, headers=headers)
return r.text.lower().count(the_word.lower())
def main():
# url = 'https://www.nytimes.com/'
medias = {
'Los Angeles Times': ['http://www.latimes.com/'],
'New York Times': ['http://www.nytimes.com/']
}
word = 'trump'
words = ['Trump', 'Facebook']
print('--- Iniciando ---')
print('Hora: ', time.strftime("%X"))
for web_name, urls in medias.items():
for url in urls:
for word in words:
count = count_words(url, word)
print('La palabra {} aparece {} veces en el sitio del {}.'.format(word, count, web_name))
if __name__ == '__main__':
main()
添加回答
举报