【问题标题】:This Python script is currently limited by the number of cities entered and I would like it to accept any number of cities [closed]这个 Python 脚本目前受输入城市数量的限制,我希望它接受任意数量的城市 [关闭]
【发布时间】:2021-04-09 02:21:11
【问题描述】:

我正在编写我的第一个 Python 脚本。我有它的工作,但我很肯定有更好的方法来做到这一点。该脚本从文本文件中获取 5 个城市的列表,并将其输出到 CSV,其中包括城市名称、最低温度、最高温度、温度和日落时间。我的脚本正好查找 5 个城市,不多也不少。我将如何更改它以搜索任意数量的城市?

这是我的脚本:

import requests
import csv

with open("cities.txt") as file:
    city1 = file.readline().replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city1)

res = requests.get(url)

data = res.json()

temp_min1 = data['main']['temp_min']
temp_max1 = data['main']['temp_max']
sunset1 = data['sys']['sunset']


with open("cities.txt") as file:
    city2 = file.readlines()[1].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city2)

res = requests.get(url)

data = res.json()

temp_min2 = data['main']['temp_min']
temp_max2 = data['main']['temp_max']
sunset2 = data['sys']['sunset']

with open("cities.txt") as file:
    city3 = file.readlines()[2].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city3)

res = requests.get(url)

data = res.json()

temp_min3 = data['main']['temp_min']
temp_max3 = data['main']['temp_max']
sunset3 = data['sys']['sunset']


with open("cities.txt") as file:
    city4 = file.readlines()[3].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city4)

res = requests.get(url)

data = res.json()

temp_min4 = data['main']['temp_min']
temp_max4 = data['main']['temp_max']
sunset4 = data['sys']['sunset']


with open("cities.txt") as file:
    city5 = file.readlines()[4].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city5)

res = requests.get(url)

data = res.json()

temp_min5 = data['main']['temp_min']
temp_max5 = data['main']['temp_max']
sunset5 = data['sys']['sunset']


outputFile = open('output.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow([city1,temp_min1,temp_max1,sunset1,city2,temp_min2,temp_max2,sunset2,city3,temp_min3,temp_max3,sunset3,city4,temp_min4,temp_max4,sunset4,city5,temp_min5,temp_max5,sunset5,])

outputFile.close()

【问题讨论】:

标签: python python-3.x csv


【解决方案1】:

这样的事情应该简化应该减少一些重复的代码(我没有测试端到端,但它应该让你走上正确的轨道)。您想使用 for 循环并对其进行迭代。 https://www.w3schools.com/python/ref_func_range.asp

import csv

with open("cities.txt") as file:
    for i in range(1, 6):
        city = file.readline(i).replace('\n', '')
        url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city)

        res = requests.get(url)

        data = res.json()

        temp_min = data['main']['temp_min']
        temp_max = data['main']['temp_max']
        sunset = data['sys']['sunset']


        outputFile = open('output.csv', 'a', newline='') #a will append a new line
        outputWriter = csv.writer(outputFile)
        outputWriter.writerow([city,temp_min,temp_max,sunset])

outputFile.close()

【讨论】:

    【解决方案2】:

    您可以更改startend 的值。

    import requests
    import csv
    
    def read_cities(start=0, end=5):
      with open("cities.txt") as file:
        cities = file.readlines()
      
      result = []
      for city in cities[start:end]:
        city = city.replace('\n', '')
        url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city)
        res = requests.get(url)
        data = res.json()
        temp_min = data['main']['temp_min']
        temp_max = data['main']['temp_max']
        sunset = data['sys']['sunset']
        result.extend([city, temp_min, temp_max, sunset])
      
      # write to output
      with open('output.csv', 'w', newline='') as outputFile:
        outputWriter = csv.writer(outputFile)
        outputWriter.writerow(result)
    
    # Test
    read_cities(1, 3)
    

    【讨论】:

    • 谢谢。这正是我所需要的。
    • 我不知道你会得到一个单行。可以接受吗?一般情况下,CSV 文件的每个数据都是单独写入行。
    【解决方案3】:

    这将为cities.txt中列出的任意数量的城市生成输出:

    import csv
    import requests
    
    with open("cities.txt") as infile, open('output.csv','w',newline='') as outfile:
        writer = csv.writer(outfile)
        for city in infile:      # iterate over lines of input
            city = city.strip()  # strip surrounding whitespace, including newline
            url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'
            res = requests.get(url)
            if res.ok:
                data = res.json()
                temp_min = data['main']['temp_min']
                temp_max = data['main']['temp_max']
                sunset = data['sys']['sunset']
                writer.writerow([city,temp_min,temp_max,sunset])
            else:
                print(f'{city} not found')
    

    cities.txt 示例:

    Madison, Wisconsin
    Honolulu, Hawaii
    

    输出:

    "Madison, Wisconsin",55,59,1609627611
    "Honolulu, Hawaii",73,78.8,1609646497
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 2019-08-04
      • 2022-01-15
      相关资源
      最近更新 更多