如果文件是用 int 而不是 string 写入的,python 中的错误处理

Error handling in python if file written with int instead of string

我有一个有效的代码并且有一个简单的问题。如果我要将文本文件从字符串更改为整数,我想对其进行错误处理。可能吗?当我将整数更改为字符串时,我只会收到错误警告,但我希望它能将字符串更改为整数。例如,如果我将“Football”更改为整数,我想得到一个错误警告。然后我想创建一个错误处理来打印例如:“文本文件内部有问题”

textfile:
Football # 8-9 # Pitch
Basketball # 9-10 # Gym
Lunch # 11-12 # Home
Reading # 13-14 # Library


from pprint import pprint
class Activity:
    def __init__(self, name, start_time, end_time, location):
        self.name = str(name)
        self.start = int(start_time)
        self.end = int(end_time)
        self.location = str(location)

 
def read_file(filename):
    activities = []
    with open(filename, 'r') as f:
        for line in f:
            activity, time, location = line.strip().split(' # ')
            start, end = time.split('-')
            activities.append(Activity(activity, start, end, location))
    return activities

activities = read_file('sample.txt')
pprint(activities)

您可以使用 isnumeric.

检查字符串是否为整数

所以让我们将输入文件更改为:

Football # 8-9 # Pitch
Basketball # 9-10 # Gym
Lunch # 11-12 # Home
3 # 13-14 # Library

现在我们要验证名称,为此我们将编写一个验证器:

class Activity:
    def __init__(self, name, start_time, end_time, location):
        self.name = self.validate_name(name)
        self.start = int(start_time)
        self.end = int(end_time)
        self.location = location

    def validate_name(self, name):
        if name.isnumeric():
            raise TypeError(f"The name: {name!r}, is not a string, please check your input file.")
        return name

    def __repr__(self):
        return f"<{type(self).__name__}, (name={self.name}, start={self.start}, end={self.end}, loc={self.location})>"

结果是 TypeError:

 line 13, in validate_name
    raise TypeError(f"The name: {name!r}, is not a string, please check your input file.")
TypeError: The name: '3', is not a string, please check your input file.

请注意,您的输入已经是字符串,因此无需使用 str(name)str(location)


编辑

上述解决方案仅验证整个名称是否为整数。对于检查输入是否使用有效字符的解决方案,我们可以使用 python 中的 re 模块和方法:

import re

def validate_input(self, name):
    regex = re.compile('\d')
    if regex.match(name):
        raise TypeError(f"The name: {name!r}, contains an integer, please check your input file.")
    return name

只要输入名称中有整数,这就会中断。先前的解决方案将继续输入,例如:Football 33 Football。此解决方案会引发错误。

您可以在 regex101

上亲自试用正则表达式