检查数字范围python

时间:2019-02-11 16:57:51

标签: python api range

我写了python脚本,其中我直接连接到api,输入数字并从中获取响应

import requests
import re
while True:
    number1 = input("nomeri ")
    num = "number"
    params = {}
    params[num]= number1
    var = requests.post('api', data = params)
    info = str(var.text)

    m = re.search('"info":{"name":\"(.+?)\"}}', info)
    if m:
      found = m.group(1)
      var = u"{}".format(found)
      text = open("text.txt", 'a')
      text.write(number1)
      print(var )
    else:
      print("not found")

现在我要重新组织它,并检查范围从000000到999999的数字,如果找到它,将其写入文本文件。范围将是0000009,000090,000091等,我如何生成它?

2 个答案:

答案 0 :(得分:0)

要始终获得六位数,可以将数字作为字符串,然后使用zfill()指定所需的位数。例如:

# the 1000000 instead of 999999 otherwise it would print/send as far as 999998
for i in range(0, 1000000):       


    # first converting the `i` to string to be able to use it's '.zfill' function
    print(str(i).zfill(6))

因此, *您只需将其调整为 而不是打印 ,{{1} }。

答案 1 :(得分:0)

如果我正确理解了您的问题和评论,则您的代码可以运行,但是您希望将其循环以发出很多请求。

要将数字格式化为带有前导零的字符串,可以使用{:06d}.format(number)

我还建议添加到列表或字典中,并在循环之后写入文件,因为这样可以更有效。

import requests
import re
result_dict = {}

# check numbers from 0 to 999.999
for i in range(10**6):
    params = {
        'number': '{:06d}'.format(i),    # a string, the number with leading zeros
    }
    resp = requests.post('api', data=params)

    m = re.search('"info":{"name":\"(.+?)\"}}', str(resp.text))
    if m:
        found_element = u"{}".format(m.group(1))
    else:
        found_element = None
    result_dict[i] = found_element

with open("text.txt", 'w') as f:
    for k, v in sorted(result_dict.items()):
        if v is not None:
            print('Value for', k, 'is', v)
            f.write('{:06d}\n'.format(k))
        else:
            print('Value for', k, 'was not found')