【发布时间】:2022-01-03 17:42:36
【问题描述】:
我希望计算特定单词在给定 URL 上显示的频率。我目前有一种方法可以为一小组 URL 和一个单词做到这一点:
import requests
from bs4 import BeautifulSoup
url_list = ["https://www.example.org/","https://www.example.com/"]
#the_word = input()
the_word = 'Python'
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 the_word.lower() in text)
count = len(words)
words_list = [ ele.strip() for ele in words ]
for word in words:
total_words.append(word.strip())
print('\nUrl: {}\ncontains {} of word: {}'.format(url, count, the_word))
print(words_list)
#print(total_words)
total_count = len(total_words)
但是,我希望能够将一组单词映射到它们各自的 URL,如下面的数据框所示。
| Target Word | Target URL |
|---|---|
| word1 | www.example.com/topic-1/ |
| word2 | www.example.com/topic-2/ |
理想情况下,输出会为我提供一个新列,其中包含单词在其关联 URL 上显示的频率。例如,'word1' 在 'www.example.com/topic-1/' 上显示的频率。
非常感谢任何和所有帮助!
【问题讨论】:
-
您是否尝试过使用
str.count()?
标签: python dataframe web-scraping beautifulsoup word-count