给定以下代码:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
import urllib.request # the lib that handles the url stuff
from bs4 import BeautifulSoup
import unicodedata
def remove_control_characters(s):
base = ""
for ch in s:
if unicodedata.category(ch)[0]!="C":
base = base + ch.lower()
else:
base = base + " "
return base
moby_dick_url='http://www.gutenberg.org/files/2701/2701-0.txt'
soul_of_japan = 'http://www.gutenberg.org/files/12096/12096-0.txt'
def extract_body(url):
with urllib.request.urlopen(url) as s:
data = BeautifulSoup(s).body()[0].string
stripped = remove_control_characters(data)
return stripped
moby = extract_body(moby_dick_url)
bushido = extract_body(soul_of_japan)
corpus = [moby,bushido]
vectorizer = TfidfVectorizer(use_idf=False, smooth_idf=True)
tf_idf = vectorizer.fit_transform(corpus)
df_tfidf = pd.DataFrame(tf_idf.toarray(), columns=vectorizer.get_feature_names(), index=["Moby", "Bushido"])
df_tfidf[["the", "whale"]]
我希望“鲸鱼”在“白鲸记”中的 tf-idf 得分相对较高,但在“武士道:日本之魂”中得分较低,而“the”在两者中得分较低。然而,我得到相反的结果。计算的结果是:
| | the | whale |
|-------|-----------|----------|
|Moby | 0.707171 | 0.083146 |
|Bushido| 0.650069 | 0.000000 |
这对我来说毫无意义。谁能指出我在思考或编码中犯的错误?
收到一只叮咚
相关分类