首先你需要读入播放器文件并将其分解成句子
>>> 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"]
以不同的方式对 Game 执行相同的操作,但将其转换为一个集合以实现唯一性和效率:
>>> 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
你应该想出一个逻辑来处理包含多种运动的句子,例如“简既踢曲棍球又踢足球。