
如何查找一个句子中是否包含python中的某个特定单词?
我有两份文件,
球员档案1乔不喜欢踢足球库马尔最喜欢的游戏是曲棍球莫希特喜欢足球纳温不喜欢板球萨钦是克里克球员萨万喜欢板球维诺德喜欢篮安迪喜欢排球
游戏文件2
hockey足球足球板球
输出期望:玩家游戏得分% Sachin是克里克球员克里克100乔不喜欢踢足球75纳温不喜欢板球100萨万喜欢板球100维诺德喜欢篮球160库马尔最喜欢的运动是曲棍球安迪喜欢排球没有比赛莫希特喜欢足球比赛
得分定义为“len(游戏)/len(匹配词)”
如果同一个玩家匹配了两场比赛,那么最高分应该会出现。
像这样,我有10000多条记录。
发布于 2020-01-17 07:07:25
首先,你需要读入播放器文件并将其拆分成句子
>>> 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执行相同的操作,但为了唯一性和效率将其转换为set:
>>> 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你应该想出一个逻辑来处理包含多项运动的句子,比如“简既打曲棍球又踢足球。
https://stackoverflow.com/questions/59775447
复制相似问题