gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:42:42 26 4
gpt4 key购买 nike

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

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) .

编辑
上述解决方案仅验证整个名称是否为整数。对于检查输入是否使用有效字符的解决方案,我们可以使用 re python中的模块和方法:
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 3 , 3 Football .此解决方案会引发错误。
您可以在 regex101 上亲自尝试正则表达式。

关于python-3.x - 如果文件用 int 而不是 string 写入,python 中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65114473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com