Я хочу отобразить соответствующие ключи для словарных слов в моем проекте. Мой код в настоящее время выводит ключи, но те же самые клавиши для любого слова, которое вы вводите. Например, если я введу 'england played well'
, возвращаемые ключи будут [737, 736, 735, 734, 733, 732, 731, 730, 729, 728]
. Если я поставлю 'Hello'
, то будут возвращены такие же ключи. Пожалуйста, посмотрите код ниже и дайте мне знать, если я делаю что-то не так
import re
import os
import math
import heapq
def readfile(path, docid):
files = sorted(os.listdir(path))
f = open(os.path.join(path, files[docid]), 'r',encoding='latin-1')
s = f.read()
f.close()
return s
DELIM = '[ \n\t0123456789;:.,/\(\)\"\'-]+'
def tokenize(text):
return re.split(DELIM, text.lower())
N = len(sorted(os.listdir('docs')))
def indextextfiles_RR(path):
postings={}
docLength = {}
term_in_document = {}
for docID in range(N):
s = readfile(path, docID)
words = tokenize(s)
length = 0
for w in words:
if w!='':
length += (math.log10(words.count(w)))**2
docLength[docID] = math.sqrt(length)
for w in words:
if w!='':
doc_length = math.log10(words.count(w))/docLength[docID]
term_in_document.setdefault(doc_length, set()).add(docID)
postings[w] = term_in_document
return postings
def query_RR(postings, qtext):
words = tokenize(qtext)
doc_scores = {}
for docID in range(N):
score = 0
for w in words:
tf = words.count(w)
df = len(postings[w])
idf = math.log10(N / (df+1))
query_weights = tf * idf
for w in words:
if w in postings:
score = score + query_weights
doc_scores[docID] = score
res = heapq.nlargest(10, doc_scores)
return res
postings = indextextfiles_RR('docs')
print(query_RR(postings, 'hello'))
Когда я запускаю сообщения, он должен вернуть привет и список ключей, связанных с ним.