Вычисляет оценку сходства между любыми двумя рецензентами, используя евклидовы расстояния - PullRequest
1 голос
/ 19 апреля 2020

Цель - прочитать файл (содержащий имя рецензента, mov ie и их рейтинги) во вложенный словарь. Затем запросите ввод данных пользователем.

  • Если ввести 1, программа запросит имя двух рецензентов, а затем выдаст результат в виде оценки сходства между ними.
  • Если ввести 2, программа запросит имя одного рецензента и сравнит их рейтинг с остальными.
  • Если ввести 3, программа завершится без выполнения каких-либо действий

Все оценки сходства рассчитываются с использованием евклидовой оценки: возьмите разницу между оценками одного и того же mov ie , возведите в квадрат, затем возведите в квадрат root конечный результат.

Пример: (В файле больше рецензентов)

Trevor Chappell’s reviews are: 
'Lawrence of Arabia':  3.0, 
'Gravity': 4.0,
'The Guns of Navarone': 3.0, 
'Prometheus': 5.0, 
'For a Few Dollars More': 3.5

Peter’s reviews are: 
'Gravity':4.5,
'For a Few Dollars More':1.0,
'Prometheus':4.0

==> Their similarity score is: (4.0 – 4.5)2  +  (3.5 – 1.0)2 + (5.0 – 4.0)2 = 0.25 + 6.25 + 1 = 7.5

Это будет ожидаемый результат: ( Жирные слова вводятся пользователем)

Give the name of the movie reviews file: <b>movie_reviews.txt</b>

What do you want to do? Input 1 for similarity between two reviewers, or Input 2 for similarity between one reviewer and all others in the database or 3 to quit: <b>1</b>
Provide Reviewer1 name: <b>Peter</b>

Provide Reviewer2 name: <b>Trevor Chappell</b>

The similarity score between Peter and Trevor Chappell is: 2.7386

What do you want to do? Input 1 for similarity between two reviewers, or Input 2 for similarity between one reviewer and all others in the database or 3 to quit: <b>2</b>

Provide Reviewer name: <b>Peter</b>

The Similarity Scores are:
Peter      and          Nancy Pollock        1.87

Peter      and          Jill Brown           1.50

Peter      and          Jack Holmes          2.87

Peter      and          Trevor Chappell      2.74

Peter      and          Mary Doyle           1.58

Peter      and          Doug Redpath         1.80

What do you want to do? Input 1 for similarity between two reviewers, or Input 2 for similarity between one reviewer and all others in the database or 3 to quit: <b>3</b>

Goodbye!

Это то, что я до сих пор:

import sys

try:
    fname = input('Enter the file name: ')
    f = open(fname, 'r') 
except FileNotFoundError:
    print('File cannot be opened:', fname)
    sys.exit()
except IOError:
    print('File cannot be opened:', fname)
    sys.exit()
#=============================================    
with open(fname) as f:
    lines = f.readlines()

d = dict()
#break down each line, and convert them into nested dictionary
#seperate reviewer name from their rating
for line in lines:
    r = line.split(',')
    reviewer    = r.pop(0)
    #add the reviewer into a new empty dictionary
    d[reviewer] = {}
    [d[reviewer].update({r[v]: float(r[v + 1])}) for v in range(0, len(r), 2)]
print(d) 
#this is the converted file data into a nested dictionary

#==================================================

print("Choose one of the following options \n Choose 1 to compare 2 reviewers \n Choose 2 to compare 1 reviewer with others \n Choose 3 to quit the program")

def getSimilarity(one, other):
    import math 
    eDiff = 0

  # looping through each movie
    for movie in d[one]:

    # if there is a match, then calculating the square difference
        if movie in d[other]:
            diff = d[one][movie] - d[other][movie] 
            eDiff += diff**2;

  # returning it
    return math.sqrt(eDiff)

def getSimilarities(one):
  # calling that reviewer with all other reviewers
  for each  in d:
    if each != one:
        print(format(one, '20s'), format(each, '20s'), round(getSimilarity(one, each),2))

# running it for all the reviewers
#for each in d:
#    getSimilarities(each)
#    print()



answer = input('Please choose an option: ')
if answer == "1":
    one = input("Enter the first reviewer name:")
    other = input("Enter the second reviewer name:")
    getSimilarity(one,other)

elif answer == "2":
    one = input("Enter the reviewer name:")
    getSimilarities(one)
elif answer == "3":
    print("Goodbye!")
    sys.exit()
else:
    print("Invalid input. Exiting now")
    sys.exit()
...