如何在 Python 2.7 中跳过空值?

问题描述 投票:0回答:1

我正在尝试读取一个简单的日期文件和相应的河流流量(立方英尺/秒,或 cfs)。有些日期没有流量。它们只是空白。我试图跳过这些空值并读取文件的其余部分。这是我的代码:

import urllib
flow = 100.0
#
page = urllib.urlopen('https://waterdata.usgs.gov/nwis/dv?cb_00060=on&format=rdb&site_no=08396500&legacy=&referred_module=sw&period=&begin_date=1905-10-01&end_date=2023-07-27')
for line in page:
    text = str(page.readline(4))
    if text == "USGS":
        page.readline(10)
        newdate = page.readline(10)
        newflow = float(page.readline(5))
        if newflow is None:
            print("Found a null!")
            continue
        if newflow <= flow:
            flow = newflow
            date = newdate
            print(date)
            print(flow)

这是我得到的错误:

回溯(最近一次调用最后一次): 文件“U:\PYTHON SCRIPTS\LOW FLOW TWO .py”,第 23 行,位于 newflow = 浮动(page.readline(5)) ValueError:无法将字符串转换为浮点数:

python-2.7 null skip
1个回答
0
投票

看起来您正在尝试跳过具有空值的行并读取文件的其余部分,但您当前的方法有一些问题。让我们一步步解决它们。

  1. 您不需要使用

    urllib
    在 Python 2.7 中打开 URL。您可以使用
    urllib2
    模块代替。

  2. 当您拨打

    page.readline(4)
    时,您正在读取每行的前 4 个字符。这可能不是你想要的。

  3. 您多次使用

    page.readline(10)
    ,这可能会导致无意中跳行。

  4. 发生错误是因为您尝试将空字符串转换为浮点数。

这是代码的修订版本,应该适合您的目的:

import urllib2

flow = 100.0

url = 'https://waterdata.usgs.gov/nwis/dv?cb_00060=on&format=rdb&site_no=08396500&legacy=&referred_module=sw&period=&begin_date=1905-10-01&end_date=2023-07-27'

response = urllib2.urlopen(url)
for line in response:
    if line.startswith("USGS"):  # Check if the line starts with "USGS"
        next(response)  # Skip the next line
        newdate = next(response).strip()  # Read and clean the date
        newflow_str = next(response).strip()  # Read and clean the flow value

        if not newflow_str:  # Check if flow value is empty
            print("Found a null!")
            continue

        newflow = float(newflow_str)
        
        if newflow <= flow:
            flow = newflow
            date = newdate
            print(date)
            print(flow)

以下是更改的作用:

  1. 我们使用
    urllib2.urlopen
    打开 URL。
  2. 我们使用
    for
    循环迭代响应的各行。
  3. 我们使用
    startswith
    检查一行是否以“USGS”开头。
  4. 我们使用
    next
    函数移动到下一行,并使用
    strip
    删除任何前导/尾随空格。
  5. 在尝试将其转换为浮点数之前,我们检查
    newflow_str
    是否为空。
  6. 我们使用正确的缩进以提高可读性。

这应该可以帮助您跳过空值并正确读取文件的其余部分。请注意,建议使用更现代的 Python 版本(例如 Python 3.x),因为 Python 2.7 已达到其生命周期并且不再受支持。

© www.soinside.com 2019 - 2024. All rights reserved.