簡體   English   中英

檢查數字范圍python

[英]check number range python

我寫了 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 等,我該如何生成它?

要實現始終為六位數,您可以將您的號碼設為字符串並使用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))

所以*你只需要用 range調整這個for loop而不是打印passing the input to your API

如果我正確理解您的問題和評論,則您的代碼可以工作,但是您希望將其循環以發出大量請求。

要將數字格式化為帶有前導零的字符串,您可以使用{: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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM