简体   繁体   English

从文件 Python 读取浮点数

[英]Reading floats from a file Python

My input file consists of a bunch of names and grades, example:我的输入文件由一堆姓名和成绩组成,例如:

Leo DiCaprio______4.5 6.5 7.5里奥·迪卡普里奥______4.5 6.5 7.5
Sean Connery______ 3.5 8.5 5.5肖恩·康纳利______ 3.5 8.5 5.5
[...] [...]

I've tried all the ways I can think of but always get the same problem, Cant convert str to float for the grades.我已经尝试了所有我能想到的方法,但总是遇到同样的问题,不能将 str 转换为 float 以获得成绩。 the goal is to calculate the average grade for every person.目标是计算每个人的平均成绩。

def average_grade(filename):
infile = open(filename, 'r')
floats = []
names = []
for line in infile:
    words = line.split('_')
    names.append(words[0])
    floats.append(float(words[1]))
infile.close()

print(names)


'''Start'''
average_grade('grades1.txt')

You are quite off the mark here.你在这里很不正常。

Your line contains more than a single underscore _ character.您的行包含多个下划线_字符。 The split result will be the following:拆分结果如下:

>>> line = 'Leo DiCaprio______4.5 6.5 7.5\n' #\n added to simulate a line read from a file.
>>> line.split('_')
['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5\n']

To access the "floats" you need to take the last item of the split result.要访问“浮点数”,您需要获取拆分结果的最后一项。

>>> floats = line.split('_')[-1].strip() #strip out the '\n'
>>> floats
'4.5 6.5 7.5'

Note however that you have multiple numbers here, separated by a space.但是请注意,这里有多个数字,用空格分隔。 You cannot convert to float all at once, you need to split them again.您不能一次全部转换为浮动,您需要再次拆分它们。

The following line will split floats in the constituant items, then it converts them to actual float type.以下行将拆分组成项中的floats ,然后将它们转换为实际的浮点类型。

>>> numbers = [float(x) for x in floats.split()]
>>> numbers
[4.5, 6.5, 7.5]

Now, I think you probably want to make a table out of the names and the numbers.现在,我想您可能想用名称和数字制作一个表格。 The easiest way to do that is to use a dict.最简单的方法是使用字典。

Also, I reccomend to dont use floats as a variable name, you can easily confuse it with the float type.另外,我建议不要使用floats作为变量名,你很容易将它与float类型混淆。 Find a better name.找到一个更好的名字。 I am not sure what that numbers are, so I will just call it numbers in the following code, but you should choose a proper name for example scores or grades or whatever they actually are.我不确定这些数字是什么,所以我将在下面的代码中将其称为numbers ,但您应该选择一个正确的名称,例如scoresgrades或它们实际上是什么。

table = {}
with open('grades1.txt', 'r') as f: #use the with statement to open files!
    for line in f:
        words = line.strip().split('_')
        name = words[0]
        numbers = [float(x) for x in words[-1].split()]
        table[name] = numbers

for k,v in table.items():
    print(k, v)

you can use regex on your input file, to get the grades of each person, plus their name.您可以在输入文件上使用正则表达式,以获取每个人的成绩以及他们的姓名。 So run a for loop on each line in the file, get the name of each person and their grades.所以在文件的每一行上运行一个 for 循环,得到每个人的名字和他们的成绩。 Once you have got the grades you can split the string of the grades by space(or whatever separates them).获得成绩后,您可以按空格(或分隔它们的任何内容)拆分成绩字符串。 This creates a list that you can work with and convert each string of the grades into float then you know how to calculate the average from there:)这将创建一个列表,您可以使用该列表并将每个成绩字符串转换为浮点数,然后您就知道如何从那里计算平均值:)

Let me know if this worked out for you!让我知道这是否适合您!

I could just give you the solution, but I want to help you understand what you do.我可以为您提供解决方案,但我想帮助您了解您的工作。

First, I change your code so that it works without a separate file.首先,我更改了您的代码,使其无需单独的文件即可工作。

That's not what you should do, but that helps me to have the code separate.这不是你应该做的,但这有助于我将代码分开。

def average_grade(data):
    floats = []
    names = []
    for line in data:
        words = line.split('_')
        names.append(words[0])
        floats.append(float(words[1]))
    print(names)

average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')

When I execute this code, I get ValueError: could not convert string to float: as well.当我执行此代码时,我得到ValueError: could not convert string to float:以及。

But why?但为什么? Well, let's then change the code:那么,让我们更改代码:

def average_grade(data):
    floats = []
    names = []
    for line in data:
        words = line.split('_')
        print(words)
        names.append(words[0])
        floats.append(float(words[1]))
    print(names)

average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')

This print(words) gives us ['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5']这个print(words)给了我们['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5']

We see that our technique to split the lines is not very good yet.我们看到我们分割线的技术还不是很好。

Let's try harder:让我们更加努力:

def average_grade(*data):
    floats = []
    names = []
    for line in data:
        words = line.split('_', 1)
        name = words[0]
        cursor = len(name)
        while line[cursor] == '_':
            cursor += 1
        grades = line[cursor:]
        print((name, grades))
        grades = grades.split()
        print((name, grades))
        grades = [float(i) for i in grades]
        avg = sum(grades) / len(grades)
        print((name, grades, avg))
        names.append(name)
        # Now, what to do with these grades? Do we add them all to the list?
        floats.append(avg)
    print(names)
    print(floats)

average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')

Now we see how the grades list evolves:现在我们看看grades列表是如何演变的:

('Leo DiCaprio', '4.5 6.5 7.5') # this is our "original", after eliminating the `_`s.
('Leo DiCaprio', ['4.5', '6.5', '7.5']) # This is a list of the strings representung the grades
('Leo DiCaprio', [4.5, 6.5, 7.5], 6.166666666666667) # This is a list of the numbers, along with their average
('Sean Connery', ' 3.5 8.5 5.5') # from here on, the same for Sean
('Sean Connery', ['3.5', '8.5', '5.5'])
('Sean Connery', [3.5, 8.5, 5.5], 5.833333333333333)
['Leo DiCaprio', 'Sean Connery']
[6.166666666666667, 5.833333333333333]

I hope that helps a bit.我希望这会有所帮助。

Note that the way how I split on the ____ part is a bit "manual";请注意,我在____部分的拆分方式有点“手动”; it would surely better to use another technique such as regular expressions.使用正则表达式等其他技术肯定会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM