猿问

用Python解析用户输入

我需要解析用户的输入,因此它具有以下格式之一:


 1321 .. 123123

或者


 -21323 , 1312321

一个数字(可以是负数),一个逗号,或两个点..,然后是另一个数字(可以是负数)。


同样,第一个数字必须小于或等于<=第二个数字。


如果输入格式不正确,请再次询问用户输入。


我有


def ask_range():

    raw = raw_input()

    raw = raw.strip(' \t\n\r')

    raw = map((lambda x: x.split("..")), raw.split(","))

    raw = list(item for wrd in raw for item in wrd)

    if len(raw) != 2:

        print "\nexpecting a range value, try again."

        return ask_range()

我不确定如何正确计算数字。


编辑


我从答案中得到帮助的解决方案是:


def ask_range():

    raw = raw_input()

    raw = raw.strip(' \t\n\r')

    raw = re.split(r"\.\.|,", raw)

    if len(raw) != 2:

        print "\nexpecting a range value, try again."

        return ask_range()


    left = re.match(r'^\s*-?\s*\d+\s*$', raw[0])

    right = re.match(r'^\s*-?\s*\d+\s*$', raw[1])

    if not (left and right):

        print "\nexpecting a range value, try again."

        return ask_range()


    left, right = int(left.group()), int(right.group())

    if left > right:

        print "\nexpecting a range value, try again."

        return ask_range()


    return left, right


阿波罗的战车
浏览 184回答 2
2回答

达令说

正则表达式对我有用,将它们直接应用于所返回的值raw_input()。例如:import res1 = '1321 .. 123123's2 = '-21323 , 1312321's3 = '- 12312.. - 9'[int(x) for x in re.findall(r'[^,.]+', ''.join(s1.split()))]=> [1321, 123123][int(x) for x in re.findall(r'[^,.]+', ''.join(s2.split()))]=> [-21323, 1312321][int(x) for x in re.findall(r'[^,.]+', ''.join(s3.split()))]=> [-12312, -9]

蝴蝶不菲

def ask_range():&nbsp; &nbsp; &nbsp; &nbsp; raw = raw_input()&nbsp; &nbsp; &nbsp; &nbsp; lis = []&nbsp; &nbsp; &nbsp; &nbsp; split1 = raw.split("..")&nbsp; &nbsp; &nbsp; &nbsp; for i in split1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lis.append(int(i))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for j in i.split(","):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.append(int(j))&nbsp; &nbsp; &nbsp; &nbsp; if len(raw) != 2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print "\nexpecting a range value, try again."&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ask_range()&nbsp; &nbsp; &nbsp; &nbsp; return lis首先使用..然后拆分,我认为这会有所帮助。
随时随地看视频慕课网APP

相关分类

Python
我要回答