import requests
from bs4 import BeautifulSoup
import operator
def start(url):
word_list = []
source_code = requests.get(url).text
soup = BeautifulSoup(source_code, "html.parser")
for text in soup.findAll("a", {"class": "result-title hdrlnk"}):
content = text.string
words = content.lower().split()
for each_word in words:
word_list.append(each_word)
clean_up_list(word_list)
def clean_up_list(word_list):
clean_word_list = []
for word in word_list:
symbols = "!@#$%^&*()_+-=[];',./\{}:\"<>?"
for i in range(0, len(symbols)):
word = word.replace(symbols[i], "")
if len(word) > 0:
clean_word_list.append(word)
create_dictionary(clean_word_list)
def create_dictionary(clean_word_list):
word_count = {}
for word in clean_word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word_count] = 1
for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):
print(key, value)
start("https://seattle.craigslist.org/search/jjj")
但是当我运行它时,我得到了这个错误
Traceback (most recent call last):
File "C:/Users/Afsal/Desktop/python/learning/html.parser.py", line 40, in <module>
start("https://seattle.craigslist.org/search/jjj")
File "C:/Users/Afsal/Desktop/python/learning/html.parser.py", line 15, in start
clean_up_list(word_list)
File "C:/Users/Afsal/Desktop/python/learning/html.parser.py", line 26, in clean_up_list
create_dictionary(clean_word_list)
File "C:/Users/Afsal/Desktop/python/learning/html.parser.py", line 35, in create_dictionary
word_count[word_count] = 1
TypeError: unhashable type: 'dict'
但是...我在评论部分找到了它,它是我尝试过的相同代码,并且效果很好
import requests
from bs4 import BeautifulSoup
import operator
def all_words(url,):
word_list = []
source_code = requests.get(url).text
soup = BeautifulSoup(source_code, "html.parser")
for before_text in soup.find_all("a", {"class": "result-title"}):
content = before_text.string
words = content.lower().split()
for each_word in words:
word_list.append(each_word)
clean_up_list(word_list)
def clean_up_list(word_list):
clean_word_list = []
for word in word_list:
symbols = "+\"*%&/()=?_-:.;,£$![]}{¦|@#¬~´"
for i in range(0, len(symbols)):
word = word.replace(symbols[i], "")
if len(word) > 0:
clean_word_list.append(word)
create_dictionary(clean_word_list)
def create_dictionary(clean_word_list):
word_count = {}
for word in clean_word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):
print(key, value)
all_words("https://cnj.craigslist.org/search/sys")
我不明白我的代码有什么问题, 有人可以请他解释出什么问题吗, 即时通讯使用python 3.7和pycharm