Я написал код алгоритма TF.IDF для pyspark, основанный на процессе MapReduce.Я хочу, чтобы мой вывод выглядел следующим образом [(слово, оценка tf_idf), (слово, оценка tf_idf), (слово, оценка tf_idf)].
Каждое слово должно быть уникальным (хотя оно появляется много раз втекст, он должен наконец появиться только один раз), что я хотел сделать с помощью функции «ReduceByKey», но это не сработало.
Кроме того, прямо сейчас вывод показывает буквы вместо слов,для какого-то резонанса мне не удается отладить.
Не могли бы вы объяснить, что мне не хватает в коде?
Большое спасибо
import string
import numpy as np
list_punct=list(string.punctuation)
text = '/dbfs/FileStore/tables/full_text.txt'
text_rdd = sc.parallelize(text)
filtered_data = text_rdd. \
map(lambda x: x.strip()). \
filter(lambda x: len(x) != 0). \
map(lambda punct : ''.join([txt.lower() for txt in punct if txt not in list_punct]))
number_of_docs = filtered_data.count()
doc_with_id = filtered_data.zipWithIndex()
tokenized_text = doc_with_id.map(lambda x: (x[1], x[0].split()) )
term_count = tokenized_text.flatMapValues(lambda x: x).countByValue()
term_document_count = tokenized_text.flatMapValues(lambda x: x).distinct()\
.map(lambda x: (x[1], x[0])).countByKey()
def tf_idf(N, term_freq, term_document_count):
result = []
for key, value in term_freq.items():
doc = key[0]
term = key[1]
df = term_document_count[term]
if (df>0):
tf_idf = float(value)*np.log(number_of_docs/df)
result.append({"doc":doc, "term":term, "score":tf_idf})
return result
tf_idf_output = tf_idf(number_of_docs, term_count, term_document_count)
tf_idf_output[:10]