【发布时间】:2021-07-02 15:34:40
【问题描述】:
我创建了一个网站列表,我的目标是在所有这些网站中找到最常用的词(不包括常用词,例如 the、as、are 等)。我尽我所能进行设置,但我意识到我的功能只是将第一个网站的单词提供到我的列表中。我创建了一个循环函数,但我相信我可能搞砸了,正在寻找修复方法。
我当前的代码是:
from bs4 import BeautifulSoup
import pandas as pd
from nltk.corpus import stopwords
import nltk
import urllib.request
list1 = ["https://en.wikipedia.org/wiki/Netflix", "https://en.wikipedia.org/wiki/Disney+", "https://en.wikipedia.org/wiki/Prime_Video",
"https://en.wikipedia.org/wiki/Apple_TV", "https://en.wikipedia.org/wiki/Hulu", "https://en.wikipedia.org/wiki/Crunchyroll",
"https://en.wikipedia.org/wiki/ESPN%2B", "https://en.wikipedia.org/wiki/HBO_Max", "https://en.wikipedia.org/wiki/Paramount%2B",
"https://en.wikipedia.org/wiki/PBS", "https://en.wikipedia.org/wiki/Peacock_(streaming_service)", "https://en.wikipedia.org/wiki/Discovery%2B",
"https://en.wikipedia.org/wiki/Showtime_(TV_network)", "https://en.wikipedia.org/wiki/Epix", "https://en.wikipedia.org/wiki/Starz",
"https://en.wikipedia.org/wiki/Acorn_TV", "https://en.wikipedia.org/wiki/BritBox", "https://en.wikipedia.org/wiki/Kocowa",
"https://en.wikipedia.org/wiki/Pantelion_Films", "https://en.wikipedia.org/wiki/Spuul"]
freq = [ ]
for i in list1:
response = urllib.request.urlopen(i)
html = response.read()
soup = BeautifulSoup(html,'html5lib')
text = soup.get_text(strip = True)
tokens = [t for t in text.split()]
sr= stopwords.words('english')
clean_tokens = tokens[:]
for token in tokens:
if token in stopwords.words('english'):
clean_tokens.remove(token)
freq = nltk.FreqDist(clean_tokens)
freq1 = freq.most_common(20)
freq[i] = pd.DataFrame(freq.items(), columns=['word', 'frequency'])
freq1
print("This is for the website: ", i, "\n", freq1)
freq1 的输出只给了我第一个网站最流行的 20 个词,我正在寻找所有网站中最流行的词。
【问题讨论】:
-
在循环之前为
freq分配一个空列表,然后通过在循环中分配freq = nltk.FreqDist(clean_tokens)来破坏它。 -
@khelwood 如果不麻烦,您能否为我提供编辑后的代码?我仍然处于中间状态,我确实应用了您的更改,但仍有一些问题。很抱歉给您带来不便
-
对不起,我不了解您的要求或代码,无法为您重写。
-
为列表使用不同的名称
freq无论如何,您似乎将它用于两件不同的事情,而不是freq[i]添加到列表中,您应该这样做freq.append()跨度> -
@RolvApneseth 谢谢你的回复 :) 你介意提供一个更清楚的例子吗?
标签: python beautifulsoup nltk urllib