簡體   English   中英

如果使用 int 而不是字符串寫入文件,則 python 中的錯誤處理

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

我有一個有效的代碼並且有一個簡單的問題。 如果我要將文本文件從字符串更改為 integer,我想對其進行錯誤處理。 可能嗎? 當我將整數更改為字符串時,我只會收到錯誤警告,但我希望它能將字符串更改為 integer。例如,如果我將“Football”更改為 integer,我想收到錯誤警告。 然后我想創建一個錯誤處理來打印例如:“文本文件內部有問題”

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 檢查字符串是否為integer

因此,讓我們將輸入文件更改為:

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)


編輯

上述解決方案僅驗證整個名稱是否為 integer。對於檢查輸入是否使用有效字符的解決方案,我們可以使用 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

只要輸入名稱中有 integer,這就會中斷。 之前的解決方案將繼續輸入,例如: Football 33 Football 此解決方案會引發錯誤。

您可以在regex101上自己試用正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM