2 回答

TA貢獻1824條經(jīng)驗 獲得超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))
你傳遞了一個列表,而你應(yīng)該傳遞一個詞來count函數(shù)。

TA貢獻1921條經(jīng)驗 獲得超9個贊
我在您的代碼中修復(fù)了一些錯誤:
首先,您在使用單詞時忘記遍歷數(shù)組,因此我在代碼的最后添加了一個 for 循環(huán)來循環(huán)遍歷這些單詞。
其次,在我這樣做之后,您的代碼返回零,所以我將 .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()
添加回答
舉報