Exercise 18: TF-IDF
Hello, I would need your help, please. I feel like I wrote the code correctly, but every time I run it, I encounter this message: ”Test Failed: AssertionError: False != True : Values have not been represented at least once or are not unique.”
import math
def main(text):
# split the text first into lines and then into lists of words
docs = [line.split() for line in text.splitlines()]
print('docs:',docs)
print('\n')
N = len(docs)
print('N:',N)
print('\n')
# create the vocabulary: the list of words that appear at least once
vocabulary = list(set(text.split()))
print('vocabulary:',vocabulary)
print('\n')
df = {}
tf = {}
for word in vocabulary:
# tf: number of occurrences of word w in document divided by document length
# note: tf[word] will be a list containing the tf of each word for each document
# for example tf['he'][0] contains the term frequence of the word 'he' in the first
# document
print('word:',word)
tf[word] = [doc.count(word)/len(doc) for doc in docs]
print('tf[word]:',tf[word])
print('\n')
# df: number of documents containing word w
df[word] = sum([word in doc for doc in docs])/N
print('df[word]',df[word])
print('\n')
# loop through documents to calculate the tf-idf values
for doc_index, doc in enumerate(docs):
tfidf = []
for word in vocabulary:
# ADD THE CORRECT FORMULA HERE. Remember to use the base 10 logarithm: math.log(x, 10)
a=tf[word][doc_index]
b=df[word]
tfidf.append(a*math.log(1/b,10))
print(tfidf)
main(text)