在python中搜索文本而不使用re-modu

2024-10-01 17:30:41 发布

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

我正在用python创建一个定义,它使用urllib2下载一个状态页并循环直到满足一个条件。你知道吗

状态页如下所示:

reportId:327686
reportName:report2
status:Running
percent_done:0

我需要

  1. 解析reportId并创建一个具有此值的变量
  2. 循环直到状态与“运行”不同

我能不使用re模块完成这个任务吗?最后,我将需要转换成一个exe使用pyinstaller,所以要避免加载大量的模块,以保持程序小。你知道吗


Tags: 模块re定义状态statusurllib2条件exe
3条回答

如果这是您的结果,并且您没有像那1guy评论的那样有更多的HTML,那么您可能可以使用startswithendswith。类似的东西(我在这里跳过了很多检查和默认值!)。。。你知道吗

if line.startswith("reportId:"):
   report_id = line.split(":")[1]

if line.startswith("status:"):
  if line.endswith("Running") == false:
    # abort processing

因为有稳定的模式可以匹配,所以非常简单:

reportIds=[]
# not written here: load report into variable s

for line in s.splitlines():
    if 'reportId' in line:
        reportIds.append(line.split(':')[1])
    if 'status' in line:
        if not line.split(':')[1] == 'Running':
            break
    # not written here: pause for some period of time

这应该做到:

import urllib2


def parse_data(raw_data):  # Name this better
    parsed_data = dict(line.split(':') for line in raw_data.splitlines())
    parsed_data['reportId'] = int(parsed_data['reportId'])
    parsed_data['percent_done'] = int(parsed_data['percent_done'])
    return parsed_data


def get_parsed_data_from_url(url):  # Name this better
    raw_data = urllib2.urlopen(url).read()
    parsed_data = parse_data(raw_data)
    return parsed_data


parsed_data = get_parsed_data_from_url('http://example.com')

# And to loop until status != 'Running', you could do this..

while get_parsed_data_from_url('http://example.com')['status'] == 'Running':
    do_some_stuff()

相关问题 更多 >

    热门问题