【问题标题】:selecting small amounts from json output in python从python中的json输出中选择少量
【发布时间】:2019-01-25 16:17:20
【问题描述】:

这是我当前的代码

def info_coin(bot, update, args):
    if args[-1] == '1':
        coin_list = args[:-1]
        opt = 1
    else:
        coin_list = args
        opt = 0
    for coin_name in coin_list:
        coin_call =requests.get("https://api.coingecko.com/api/v3/coins/" + str(coin_name)).json()
        coin_isd = coin_call ['description']['en']
        print(coin_isd)
        update.message.reply_text(coin_isd)

我想进一步选择 ['en'] 以仅从中选择一定数量的文本。原因是我的信息发送时间过长。

【问题讨论】:

  • 您的问题不清楚。你能扩展吗?

标签: python json bots telegram chatbot


【解决方案1】:

如果coinCall['description']['en'] 是一个字符串,您可以对其进行切片。

假设您想将字符串限制为 10 个字符,您可以将代码更新为以下内容

def infoCoin(bot,update,args,max_string=10):
    if args[-1] == '1':
        coin_list=args[:-1]
        opt=1
    else:
        coin_list=args
        opt=0
    for coinName in coin_list:
        coinCall =requests.get("https://api.coingecko.com/api/v3/coins/"+str(coinName)).json()
        coinIsd = coinCall ['description']['en'][:max_string]
        print(coinIsd)
        update.message.reply_text(coinIsd)

请注意,如果字符串的长度小于max_string,则只会得到整个字符串

In [873]: x='string'

In [874]: x[:10]
Out[874]: 'string'

【讨论】:

    【解决方案2】:

    您可以将变量传递给函数并决定需要从字典中提取多少个字符。就像在下面的示例中一样,我传递了 100,因此只会提取前 100 个字符。 试试这个代码:

    import requests
    
    
    def infoCoin(args, total_string_length_to_send):
            coinCall =requests.get("https://api.coingecko.com/api/v3/coins/"+args).json()
            print(coinCall['description']['en'][:total_string_length_to_send])
    
    infoCoin('bitcoin', 100)
    

    【讨论】:

    • 如果我的用户声明了 infoCoin 变量并且我想确保只有 api 响应的前 100 个字符会发送给他们,我会怎么做?
    • 您可以将其硬编码为 100。coinCall['description']['en'][:100]
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多