如何从文件中找到句子中的最大数字然后打印?

时间:2018-11-17 17:19:28

标签: python

我只想知道如何在一个句子中找到最大的数字,然后打印出来,因为我正在从事一个涉及放置球员姓名和获得多少分的项目。文件中的格式如下:播放器1(用户名)获得20分。我不知道这是否正确,但这可能与此有关

numbers = [1,2,3,4,5,6,7]
print('The biggest number is: ' + str(max(s)))

但是我想要它,以便它从文件中的句子中获取最大的数字,并且文件格式看起来像是“约翰有58分”。

3 个答案:

答案 0 :(得分:2)

此代码将从文件“数据”中读取数据,并使用您提供的格式将其内容转换为python dict:(玩家)具有(点)点,然后找到具有最大点数的玩家并打印该玩家名称和他的观点。

applogging-test

功能证明:

import operator

file = open('data', 'r')
file_content = file.read().splitlines()
file.close()

users_points = {i.split()[0]: int(i.split()[2]) for i in file_content}
best_player = max(users_points.items(), key=operator.itemgetter(1))[0]

print('player with maximum points is {}, this player has {} points'.format(best_player, users_points[best_player]))
print(sorted(users_points.values())) # This will print points of all players

导致输出:

s = '''john has 58 points
bob has 46 points
fred has 0 points
leo has 27 points
max has 34 points'''

import operator

file_content = s.splitlines() # no file available here, but result is the same

users_points = {i.split()[0]: int(i.split()[2]) for i in file_content}
best_player = max(users_points.items(), key=operator.itemgetter(1))[0]

print('player with maximum points is {}, this player has {} points'.format(best_player, users_points[best_player]))
print(sorted(users_points.values())) # This will print points of all players

best_players = sorted(users_points, key=users_points.get, reverse=True)
for bp in best_players:
    print('{} has {} points'.format(bp, users_points[bp]))

答案 1 :(得分:1)

熊猫的解决方案:

import pandas as pd

假设文件看起来像

john has 58 points
bob has 46 points
fred has 0 points
leo has 27 points
max has 34 points

导入很简单,并且可以自动处理基本类型转换

df = pd.read_table(filename, sep=' ',  usecols=[0,2], names=['name', 'points'])

并进行排序

srtd_data = df.sort_values('points', ascending=False)

您所有的请求都非常容易实现:
获奖者名单和他的观点:

srtd_data.loc[0].values

['john' 58]

所有已排序点的列表:

srtd_data.points.values

[58 46 34 27  0]

排序句子:

srtd_data.apply(lambda x: '{} has {} points'.format(x[0], x[1]), axis=1))

0    john has 58 points
1     bob has 46 points
4     max has 34 points
3     leo has 27 points
2     fred has 0 points
dtype: object   

答案 2 :(得分:1)

您可以这样做:

f = open("file.txt","r")
lines = list(f) #create a list of strings
f.close() #don't forget to close our files when we're done. It's good practice.
modified_lines = [] #empty list to put our modified lines in (extracted number, original line)
for line in lines: #iterate over each line
    if line.strip(): #if there's anything there after we strip away whitespace
        score = line.split(' ')[2] #split our text on every space and take the third item
        score = int(score) #convert the string of our score into a number
        modified_lines.append([score, line]) #add our modified line to modified_lines

#sort our list that now has the thing we want to sort based on is first
sorted_modified_lines = sorted(modified_lines, reverse = True )

#take only the string (not the number we added before) and print it without the trailing newline.
for line in sorted_modified_lines:
    print(line[1].strip()+"\n")