如何在python中验证字符串和整数输入?

时间:2015-10-20 18:30:45

标签: python

我的目标是在用户输入特定年份时将文本行打印到新文档中。到目前为止,该部分工作正常。但是,我不确定如何处理用户输入“all”以表示他们想要将所有数据复制到新文件中。你可以看到我尝试理解试验的失败尝试以及下面的块:

filename = input("Enter an output file name: ")
file_write = open(filename, 'w')
file_read = open("polio.txt")
user_year = input("Enter a year: ")
while True:
    try:
        for line in file_read:
            year = int(line[68:74])
            millenium = int(line[68:69])
            century = int(line[68:70])
            decade = int(line[68:71])
            user_year == int(user_year)
            if user_year == year:
                file_write.write(line)
            if user_year == millenium:
                file_write.write(line)
            if user_year == century:
                file_write.write(line)
            if user_year == decade:
                file_write.write(line)
    except ValueError:
        if user_year == {"", "all", "ALL"}:
                file_write(line[:74])
        file_read.close

基本上,我需要做的就是找到一种方法来比较用户想要的年份和文本文件中的年份,同时还要评估空字符串和包含短语“ALL”或“all”的字符串

2 个答案:

答案 0 :(得分:1)

我已经为您提供了一些内容,希望他们可以帮助您了解各个组件,以便您可以根据自己的需要构建程序。

文件访问

首先,接受的越多," Pythonic"进行文件访问的方式是使用"上下文管理器"。值得庆幸的是,open语句支持:

with open('polio.txt') as f:
    # do stuff here

无论是否出现错误,无论何时上下文都会自动处理关闭文件。这可以防止您必须跟踪文件关闭并可能出错。如果它困扰你,你可以打开文件打开并处理成不同的函数以减少额外的嵌套。

更好地请求宽恕而不是接受

另一种Python习语是,请求宽恕比接受更好。而不是试图检查字符串是否是一个数字,正如另一个回答者建议的那样,只是尝试将其转换为整数并处理它不是的情况:

try:
    user_year = int(user_year)
except ValueError:
    pass

然后您可以轻松检查该值是否为" all"后面。

检查项目是否属于可转换

您正在尝试查看用户是否已通过某些变体" all"这里:

if user_year == {"", "all", "ALL"}:
    # do stuff here

这将永远不会有效,因为user_year永远不会是一组字符串,你要比较它们。而是使用in语句来测试iterable是否包含项目:

if user_year in {"", "all", "ALL"}:
    # do stuff here

答案 1 :(得分:0)

您可以使用str.isdigit()检查输入是否为有效整数,如下所示:

filename = input("Enter an output file name: ")
file_write = open(filename, 'w')
file_read = open("polio.txt")
user_year = input("Enter a year: ")

# check for empty string after removing white spaces
# OR check if answer is all or ALL
all_option_selected = user_year.strip().lower() in {"", "all"}
# calculate year once outside the loop if input is valid integer
if user_year.strip().isdigit():
    user_year = int(user_year)
else:
    user_year = None
try:
    while True:

        for line in file_read:
            year = int(line[68:74])
            millenium = int(line[68:69])
            century = int(line[68:70])
            decade = int(line[68:71])

            if all_option_selected:
                file_write(line[:74])
                # continue with next line since user did not enter a valid year
                continue

            if user_year is None:
            # user year is not valid number and all option was not selected
            # so we break out of the loop since input is invalid
                break
            if user_year == year:
                file_write.write(line)
            if user_year == millenium:
                file_write.write(line)
            if user_year == century:
                file_write.write(line)
            if user_year == decade:
                file_write.write(line)
finally:
    file_read.close()
    file_write.close()