读取文件,然后将字符串转换为浮点数,然后查找平均,总和,最低和最高总计

时间:2019-04-11 19:36:22

标签: python-3.x

我遇到的问题是,当程序读取文件时,它正在读取名称以及必要的数字,但是我无法将数字转换为浮点数。文本文件称为“ gym.txt”,这是我必须阅读的内容。我在低级别的编码课程中,所以代码应该有点基础。以下是“ gym.txt”的内容:

5
Albert 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8
John 9.1 9.4 9.6 9.8 9.4 9.3 9.9 9.1
Jay 9.2 9.3 9.0 9.9 9.4 9.3 9.9 9.1
Henry 9.4 9.3 9.9 9.1 9.5 9.5 9.6 9.8
Walter 9.2 9.3 9.4 9.3 9.9 9.1 9.6 9.0

5表示竞争对手的数目,并且在这些得分中,每个人的最高和最低得分被丢弃。这样,总数就变成了6,不包括每个人的最低和最高分数。

我尝试逐行读取文件,如下面的代码所示,由于名称与数字在同一行,因此将其转换为float失败。我计划对每个名称和分数集(如果可行)使用此代码。

f=open('gym.txt','r')
judges=6
contestants=f.readline().rstrip("\n")
print(contestants)
albert=str(f.readline().rstrip('\n'))
albert_list=float(albert.strip("Albert"))
print(albert_list)

预期结果如下:

The number of contestants is 5.

Contestant          Scores
_______________________________________________

Albert  9.3 9.0 9.9 9.5 9.5 9.6 9.8 

John    9.4 9.6 9.8 9.4 9.3 9.9 9.1 

Jay 9.3 9.0 9.9 9.4 9.3 9.9 9.1 

Henry   9.3 9.9 9.1 9.5 9.5 9.6 9.8 

Walter  9.3 9.4 9.3 9.9 9.1 9.6 9.0 
Total score of Albert is 9.48.
Total score of John is 9.43.
Total score of Jay is 9.37.
Total score of Henry is 9.52.
Total score of Walter is 9.32.
The highest total score amongst the contestants is 9.52.
The lowest total score amongst the contestants is 9.32.

格式化对我来说不是一个大问题,我只是对程序本身的帮助感兴趣。这是我得到的错误:

5
Traceback (most recent call last):
  File "C:/Users/theon/PycharmProjects/untitled/CS 1113/gymnasium.py", line 6, in <module>
    albert_list=float(albert.strip("Albert"))
ValueError: could not convert string to float: ' 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8'

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

with open('gym.txt', 'r') as file:
    all_file = file.read().strip()  # Read and remove any extra new line
    all_file_list = all_file.split('\n')  # make a list of lines
    number_of_contestant = all_file_list.pop(0)  # get the first line (removes form the all_file_list as well)
    data = []
    # Except for names, number will be converted to floats, Rejects the 1st max and min number too
    for line in all_file_list:
        line_list = line.split()
        temp_list = [x if i == 0 else float(x) for i, x in enumerate(line_list)]  # convert string float to Float
        temp_list.remove(max(temp_list[1:]))  # Remove the max
        temp_list.remove(min(temp_list[1:]))  # Remove the min
        data.append(temp_list)
    print('The number of contestants is {}.'.format(number_of_contestant))
    print('_' * 50)
    print('{} {:^50}'.format('Contestent', 'Scores'))
    print('_' * 50)
    for row in data:
        print('{:<15} {}'.format(row[0], '  '.join([str(x) for x in row[1:]])))
    print('_' * 50)
    print('_' * 50 + '\n')
    total_score = []
    for row in data:
        row_total_score = sum(row[1:]) / len(row[1:])
        total_score.append(row_total_score)
        print('{:<30} {:.2f}'.format('Total Score of ' + row[0] + ' is: ', row_total_score))
    print('_' * 50 + '\n' + '_' * 50 + '\n')
    print('The highest total score amongst the contestants is {:.2f}'.format(max(total_score)))
    print('The lowest total score amongst the contestants is {:.2f}'.format(min(total_score)))

输出:

The number of contestants is 5.
__________________________________________________
Contestent                       Scores
__________________________________________________
Albert          9.2  9.3  9.5  9.5  9.6  9.8
John            9.4  9.6  9.8  9.4  9.3  9.1
Jay             9.2  9.3  9.4  9.3  9.9  9.1
Henry           9.4  9.3  9.5  9.5  9.6  9.8
Walter          9.2  9.3  9.4  9.3  9.1  9.6
__________________________________________________
__________________________________________________

Total Score of Albert is:      9.48
Total Score of John is:        9.43
Total Score of Jay is:         9.37
Total Score of Henry is:       9.52
Total Score of Walter is:      9.32
__________________________________________________
__________________________________________________

The highest total score amongst the contestants is 9.52
The lowest total score amongst the contestants is 9.32

参考文献:

  1. 使用
  2. 格式
  3. 列表理解
  4. 最小,最大

答案 1 :(得分:0)

使用熊猫可以做到这一点

import pandas as pd
import numpy as np

df=pd.read_csv('gym.txt', sep=' ', header=None).set_index(0)
df=df.where(df.values != df.min(axis=1)[:,None])
df=df.where(df.values != df.max(axis=1)[:,None])
df['mean'] = df.mean(axis=1)
print('Contestant             Scores')
print('----------------------------------------')
print(df.to_string())
print('----------------------------------------')
print('''The highest total score amongst the contestants is {:.2f} achieved by {}
The lowest total score amongst the contestants is {:.2f} achieved by {}'''\
.format(max(df['mean']),np.argmax(df['mean']),min(df['mean']),np.argmin(df['mean'])))

Out:'''
Contestant             Scores
----------------------------------------
          1    2    3    4    5    6    7    8      mean
0                                                       
Albert  9.2  9.3  NaN  NaN  9.5  9.5  9.6  9.8  9.483333
John    NaN  9.4  9.6  9.8  9.4  9.3  NaN  NaN  9.500000
Jay     9.2  9.3  NaN  NaN  9.4  9.3  NaN  9.1  9.260000
Henry   9.4  9.3  NaN  NaN  9.5  9.5  9.6  9.8  9.516667
Walter  9.2  9.3  9.4  9.3  NaN  9.1  9.6  NaN  9.316667
----------------------------------------
The highest total score amongst the contestants is 9.52 achieved by Henry
The lowest total score amongst the contestants is 9.26 achieved by Jay'''