简体   繁体   English

元组| 将字符串转换为浮点数

[英]Tuples | Converting Strings to Floats

I'm following along with a Great Course tutorial for learning Python, and this code doesn't seem to work. 我正在跟着学习Python的精彩课程教程一起学习,但是这段代码似乎不起作用。

#Open File
filename = input("Enter the name of the data file: ")
infile = open(filename, 'r')

#Read in file
datalist = []

for line in infile:
    #Get data from line
    date, l, h, rf = (line.split(','))
    rainfall = float(rf)
    max_temp = float(h)
    min_temp = float(l)
    m, d, y = (date.split('/'))
    month = int(m)
    day= int(d)
    year=int(y)
    #Put data into list
    datalist.append([day,month,year,min_temp,max_temp,rainfall])

I'm trying to import a csv file, then create a tuple. 我正在尝试导入一个csv文件,然后创建一个元组。 The problem occurs when I'm converting the values in the tuple to floats. 当我将元组中的值转换为浮点数时,会发生问题。 It works fine until it runs through the file. 直到通过文件运行,它才能正常工作。 Then it presents me with this error: 然后它向我显示此错误:

Traceback (most recent call last): File "C:/Users/Devlin/PycharmProjects/untitled3/James' Programs/Weather.py", line 16, in rainfall = float(rf) ValueError: could not convert string to float:` 追溯(最近一次通话最近):文件“ C:/ Users / Devlin / PycharmProjects / untitled3 / James's Programs / Weather.py”,第16行,降雨= float(rf)ValueError:无法将字符串转换为float:

Any ideas on what am doing wrong? 有什么想法做错了吗?

It's hard to tell what exactly are you doing wrong without seeing the input file itself, but what seems to be wrong here (besides the fact that your values in a file seem to be comma-separated and that you might have been better off using Python stdlib's csv module) is that you're encountering a string somewhere when iterating over the lines, and are trying to convert that to float which is a no go: 在不看到输入文件本身的情况下很难说出您到底在做什么错,但是这里似乎有什么错误(除了文件中的值似乎用逗号分隔以及使用Python可能会更好之外)。 stdlib的csv模块)是您遍历行时在某处遇到字符串,并尝试将其转换为float,这是不可行的:

>>> float('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'spam'

One of the solutions would be to simply skip the strings you're encountering, and you can choose between two approaches there ( LBYL (Look Before You Leap) vs EAFP (Easier to Ask for Forgiveness than Permission) ), and, in a nutshell, I suggest you go with the latter since it's generally preferred due to the gap that exists between checking and using, which means that things can change out from under you, and oftentimes you'll have to handle the error in any case, even if you check first. 解决方案之一就是简单地跳过您遇到的字符串,您可以在两种方法之间进行选择( LBYL(跳跃前请先看)EAFP(要求更容易获得宽恕) ),并且简而言之,我建议您选择后者,因为由于检查和使用之间存在间隙,因此通常优先选择后者,这意味着事情可能会从您的角度改变,有时即使在任何情况下,您都必须处理错误,即使您先检查一下。 Apart from that, instead of manually closing file-like objects later on (which you seem to have forgotten to do), I suggest using with statement as a context manager which automatically manages that for you. 除此之外,我不建议以后手动关闭类似文件的对象(您似乎已经忘记这样做了),我建议使用with语句作为上下文管理器,它自动为您管理。 So, taking all that into account, something along the following lines should do the trick (disclaimer: not thoroughly tested): 因此,考虑到所有这些,应该采取以下措施(免责声明:未经彻底测试):

import csv

data = []

filename = input('Enter the name of the data file: ')

with open(filename) as f:
    reader = csv.reader(f, delimiter=',', skipinitialspace=True)
    for line in reader:
        try:
            date, (l, h, rf) = line[0], map(float, line[1:])
            m, d, y = map(int, date.split('/'))
        except ValueError as e:
            print('Skipping line: %s [because of: %s]' % (line, e))
            continue
        data.append([d, m, y, l, h, rf])

Hopefully this is enough to get you back on track ;-) 希望这足以让您重回正轨;-)

Review your csv file. 查看您的csv文件。

It is hard to say without seeing what's in the file, but the most likely explanation (according to the error message) is that you have a line for which the forth value is empty, eg: 不查看文件中的内容很难说,但是最有可能的解释(根据错误消息)是,您有一行第四值为空,例如:

2018-01-30,5,12,

So the rf variable would be empty when parsing that line, and the you would get that ValueError when trying to cast the value as a float. 因此, rf变量在解析该行时将为空,并且在尝试将值转换为浮点型时会得到ValueError

Also, some advice on how to do it better: 另外,关于如何做得更好的一些建议:

  • You may want to split your line first, then count how many data fields it has, and then discarding it before assigning the whole line to date, l, h, rf . 您可能要先分割行,然后计算它有多少个数据字段,然后在分配整行到date, l, h, rf之前丢弃它。 Something like this: 像这样:

` `

for line in infile:
    # Get data from line. Use strip() to avoid whitespace
    items = line.strip().split(',')
    if len(items) != 4:
        # skip the iteration - do nothing with that malformed line
        continue
    date, l, h, rf = items

` `

  • You may want to have a look at the csv module for reading/writing csv files easily. 您可能想看看用于轻松读取/写入csv文件的csv模块

The error means you that the string you are trying to cast a float is actually not a number. 该错误意味着您尝试转换浮点数的字符串实际上不是数字。 In your case, it looks like it's an empty string. 在您的情况下,它看起来像是一个空字符串。 It's probably because the last line of your file is empty, so you can check it at the beginning of your loop and break or continue if it is. 可能是因为文件的最后一行是空的,所以您可以在循环开始时检查它,然后中断或继续。 An other strategy would be to catch the error, but it would then ignore a malformed line when you could want to be alerted of it, so it's up to you to pick the one that suites you. 另一种策略是捕获错误,但是当您希望收到错误提示时,它将忽略格式错误的行,因此您可以选择适合您的错误行。

Using square brackets also puts your values in a list, not in a tuple. 使用方括号还将您的值放在列表中,而不是在元组中。 You need parenthesis for that. 为此,您需要括号。

And you should also close your files when you are done. 完成后,您还应该关闭文件。

Python also has a CSV module you may find useful. Python还有一个CSV模块,您可能会觉得有用。

#Open File
filename = input("Enter the name of the data file: ")
infile = open(filename, 'r')

#Read in file
datalist = []

for line in infile:
    if line.strip() == '': # If the line only contains spaces
        continue           # Then, just skip it

    # Some stuff ...

    # Put everything in a tuple that we add to our list
    datalist.append((day,month,year,min_temp,max_temp,rainfall))

infile.close() # Close the file

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

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