是否有一个函数可以将变量“自动完成”到所需的库中?

2024-09-27 21:33:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个变量设置为我在库中的变量。有这样的命令吗

我试图做一个简单的时区转换器,我想检查输入变量,但我只能检查pytz列表中的变量,所以我想'自动完成'变量。我能做这个吗

import time
import pytz
country = input("enter country")

from datetime import datetime
from pytz import timezone

fmt = "%H:%M %p"

now_utc = datetime.now(timezone('UTC'))
print (now_utc.strftime(fmt))

from pytz import all_timezones
if country in all_timezones:
    country = #completed country in list 'all_timezones'
    timecountry = now_utc.astimezone(timezone(country))
    print (timecountry.strftime(fmt))

Tags: infromimportdatetimeallcountrynowutc
1条回答
网友
1楼 · 发布于 2024-09-27 21:33:00

因此,您要寻找的是一种将用户输入与all_timezones中的字符串匹配并查找有效时区的方法

据我所知,没有内置的功能可以做到这一点,你必须自己去做

这不是一个立即的任务,因为你可能有多种选择(假设用户输入只是'欧洲'),你必须考虑到这一点

可能的方法如下:

import datetime
import time
import pytz

country = input("Contry name: ")
now_utc = datetime.datetime.now(pytz.timezone('UTC'))

fmt = "%H:%M %p"

while True:
    possible_countries = [ac for ac in pytz.all_timezones if country in ac]
    if len(possible_countries) == 1:
        cc = possible_countries[0]
        timecountry = now_utc.astimezone(pytz.timezone(cc))
        print(timecountry.strftime(fmt))
        break
    elif len(possible_countries) > 1:
        print("Multiple countries are possible, please rewrite the country name")
        for cs in possible_countries:
            print(cs)
        country = input("Contry name: ")
    else:
        print("No idea of the country, here are the possible choices")
        for cs in pytz.all_timezones:
            print(cs)
        country = input("Contry name: ")

通过列表理解,我查找all_timezones中包含用户输入的所有字符串。如果只有一个,则脚本将假定该脚本是正确的,并执行任务。否则,如果有多个可能性,它将打印它们(每行一个,使用for循环,但您可以只打印列表,使其在屏幕上更短),然后要求用户重写国家名称。如果没有匹配项,它只打印所有可能的。您可能会发现在命令行上看到它很难看,但是您应该了解这个想法,然后改进它

如果您还想检查用户输入中的拼写错误。。。这要困难得多

相关问题 更多 >

    热门问题