如果有值,则Python通过boolean循环

2024-05-19 16:35:06 发布

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

我试图编写一个脚本,在其中我检查一页的名字。在我继续总结问题之前。这个页面是已知的flick-这意味着一旦你进入这个页面,它可以列出你的名字。下一次刷新页面时,它会返回空的名字列表,下一次它会再次列出你的名字。(这是我试图做的进一步想法)但是我已经创建了一个自己的脚本,作为用户,我们可以更容易地测试它。你知道吗

我没有请求,而是创建了一个txt文件,以便更轻松地运行程序

我想做的是:

我想使脚本,使它打开txt每一个循环,它检查是否有名单中的名字,然后我们打印出来只有一次。如果没有名字-那么我想做一个计数器,检查名字是否真的是空的,也就是说,在这种情况下,我想创建一个计数器来确认,并声明列表中没有名字。这意味着在打开txt文件的5个之后,列表中没有任何名字在这5个之后。然后我们可以声明它实际上是空的。你知道吗

若计数器已经确认它是空的,那个么我们循环直到我们找到名字并再次打印它,然后我们像前面一样重新开始。你知道吗

我试过的是,我认为在编写代码时有一个小问题,我可能会把自己搞糊涂,或者把自己弄得比实际应该的更复杂。你知道吗

count = 0
last_names = []
names_checker = False

while True:

    with open('./test.txt') as f:
        new_product_values = json.load(f)

    # {'name': 'Random names', 'url': 'www.stackoverflow.com', 'names': []}

    if names_checker == False:

        if not new_product_values['sizes']:
            count += 1
            time.sleep(1)

        if count == 5:
            names_checker = True
            count = 0
            logger.success('Declare value as No names')

        else:
            names_checker = True

    elif names_checker == True:

        while True:


            if new_product_values['names'] != last_names:

                print("NEW NAMES!")
                print(new_product_values['names'])
                last_names = new_product_values['names']
                logger.status(last_names)
                names_checker = False
                break

            else:
                logger.warn("Nothing found - sleep 1")
                time.sleep(1)

text file:

{'name': 'Random names', 'url': 'www.stackoverflow.com', 'names': []}

在这种情况下,我的预期结果是:

如果列表中没有名称,我们在计数器中添加一个,如果下一个循环仍然给我们空名称,那么我们在计数器中添加另一个,直到它到达计数器5,当它到达计数器5时,我希望它声明为列表为空。每当它为空时,我们都要循环,直到找到名称为止。一旦我们找到了要声明列表不是空的名字,就把名字打印出来,然后用计数器重新开始。你知道吗


Tags: txt脚本true声明列表newifnames
1条回答
网友
1楼 · 发布于 2024-05-19 16:35:06

你的分析是对的:你想得太多了。

首先,把你正在做的事情分成几个简单的步骤

                +             +
  +     -> |Get the data from the page| <        -+
  |             +      -+      +                   |
  |                           |                                |
  |                           v                                |
  |                                                            |
  |          +                     -+     |
  |          |Get the data into a nice format (e.g. list)|     |
  |          +         +            +     +   +
  |                             |                              |      |
  |                             |                     +    +      |
  |                          + +                     |               |
  |                          |                        |         +      -+
  |                          v                        |         |wait for data|
  |                                                   |         +      -+
  |         +             +              |
  |         |Do we actually have data? |              |                 ^
  |         +   +  -+      -+              |flick            |no data
  |                |     |                            |                 |
+-+   +         |     |        +         -+        -+  -+
|do stuff|    <  +     +  >   |Is this a flick or is there really no data?|
+    +     yes         no     +                     -+

您会看到flick和no data最终都返回以获取数据。你知道吗

如果将上述步骤放入python代码中,将得到如下结果:

def get_data():  # just an example
    r = requests.get(...)
    r.raise_for_status()
    return r

def parse_data(text, _old=[]):  # list is mutable => preserved across calls
    """convert the text to a list of names. If there are no (new) names, the list is empty"""
    ...
    if new_data not in _old:
        _old.append(new_data)
        return new_data
    else:
        return []

def delay_get_data(by):
    time.sleep(by)
    return get_data()

def do_stuff(names):
    ...

这样拆分不仅可以让您更好地阅读和理解代码,还可以为您提供一种更改各个部分的方法:如果您想使用本地文件/数据进行测试,只需重写get_data,而无需更改任何其他内容:

def get_data():
    if random.randint(0, 1):  # simulate flicks
        return empty_sample_data
    else:
        return random.choice(sample_data_with_names)

按照上面的结构图,您现在可以首先获取数据,检查它并在获取新数据之前执行正确的操作,方法是查看one循环中的counter

WAIT_TIME = 10*60
counter = 0
data = parse_data(get_data())
while True:
    if data:
        counter = 0
        do_stuff(data)
        print("I got the data and did {stuff}. Now I'll wait and repeat with new names")
        data = parse_data(delay_get_data(WAIT_TIME))
    else:
        counter += 1
        if counter >= 5:  # cosmic rays may increase ``counter`` by 2 instead of 1
            counter = 0
            print("I think there actually isn't any data. I'll wait and then check again")
            data = parse_data(delay_get_data(WAIT_TIME))
        else:
            data = parse_data(get_data())  # no delay, it was probably just a flick

如果新数据很快进入,并且您决定不需要那么多日志记录,那么您也可以将counter取出。你知道吗

相关问题 更多 >