是否有将变量'autocomplete'到所需库的函数?



我正试图将一个变量设置为库中的一个变量。有这样做的命令吗?

我正在尝试制作一个简单的时区转换器,我想检查输入变量,但我只能从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))

因此,您正在寻找一种将用户输入与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循环,但您可以只打印列表,使其在屏幕上更短),然后要求用户重写国家名称。如果没有匹配,它只打印所有可能的结果。你可能会发现在命令行上看到它很难看,但你应该明白这个想法,然后改进它

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

最新更新