Сначала вам нужно прочитать файл Player и разбить его на предложения
>>> with open ('testfiles/player.txt') as f:
... sentences = []
... for line in f:
... sentences.append (line.strip ())
>>> sentences
['Sachin was a cricket player', 'Mohit likes soccer game', 'Kumar favourite game is hockey', "Joe doesn't like to play football"]
Сделайте то же самое для игры другим способом, но конвертируйте его в набор для уникальности и эффективности:
>>> with open ('testfiles/games.txt') as f:
... games = set ([line.strip () for line in f])
...
>>> games
{'hockey', 'crick', 'soccer', 'volleyball', 'badminton'}
Теперь мы просто ищем ключевое слово в предложении и получаем вывод ниже.
>>> game_score = {}
...game_found = set ()
...for sentence in sentences:
... for game in games:
... if game in sentence:
... game_score.setdefault (game, [sentence, '100%']) # Save game name as key and set sentence a list of value that include sentence and % matching
... game_found.add (sentence) # Save the game name that are found to be checked against the game name that isn't found
>>> game_score
{'hockey': ['Kumar favourite game is hockey', '100%'], 'crick': ['Sachin was a cricket player', '100%'], 'soccer': ['Mohit likes soccer game', '100%']}
>>> game_found
{'Mohit likes soccer game', 'Kumar favourite game is hockey', 'Sachin was a cricket player'}
Сравните game_found с предложениями игрока и добавьте игры, не найденные в game_score:
>>> for i, sentence in enumerate (sentences):
... if sentence not in game_found:
... game_name = 'null-%d' % i # Dictionary key cannot contain duplicate
... game_score.setdefault (game_name, [sentence, 'No match'])
...
>>> game_score
{'hockey': ['Kumar favourite game is hockey', '100%'], 'crick': ['Sachin was a cricket player', '100%'], 'soccer': ['Mohit likes soccer game', '100%'], 'null-3': ["Joe doesn't like to play football", 'No match']}
Наконец, напечатайте результаты:
>>> print ('Output%sGame%sMatching Score' % (' ' * 35, ' ' * 10))
...for k in game_score:
... spacing = 41 - len (game_score [k][0])
... print ('%s%s%s%s%s' % (game_score [k][0], ' ' * spacing, k, ' ' * (55 - (len (game_score [k][0]) + spacing + len (k))), game_score [k][1]))
...
Output Game Matching Score
Kumar favourite game is hockey hockey 100%
Sachin was a cricket player crick 100%
Mohit likes soccer game soccer 100%
Joe doesn't like to play football null-3 No match
Вы должны придумать логику c, чтобы иметь дело с предложениями, которые имеют несколько видов спорта, таких как «Джейн играет в хоккей и футбол.