Python 程序来搜寻网页并获得出现频率最高的单词
我们的任务是搜寻网页并统计单词频率。最终检索出出现频率最高的单词。
首先,我们正在使用 request 和 BeautifulSoup 模块,在这些模块的帮助下创建网络爬虫并从网页中提取数据并存储到列表中。
示例代码
import requests
from bs4 import BeautifulSoup
import operator
from collections import Counter
def my_start(url):
my_wordlist = []
my_source_code = requests.get(url).text
my_soup = BeautifulSoup(my_source_code, 'html.parser')
for each_text in my_soup.findAll('div', {'class':'entry-content'}):
content = each_text.text
words = content.lower().split()
for each_word in words:
my_wordlist.append(each_word)
clean_wordlist(my_wordlist)
# Function removes any unwanted symbols
def clean_wordlist(wordlist):
clean_list =[]
for word in wordlist:
symbols = '!@#$%^&*()_-+={[}]|\;:"<>?/., '
for i in range (0, len(symbols)):
word = word.replace(symbols[i], '')
if len(word) > 0:
clean_list.append(word)
create_dictionary(clean_list)
def create_dictionary(clean_list):
word_count = {}
for word in clean_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
c = Counter(word_count)
# returns the most occurring elements
top = c.most_common(10)
print(top)
# Driver code
if __name__ == '__main__':
my_start("https://tutorialspoint.com/python3/python_overview.htm/")
输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP