如何检测文本文件导入数组中字符串数据的实际类型?
问题描述
我编写了一个函数,可借助辅助函数检查输入数据是否能转换为int或float,但无法检测从文本文件导入到数组中、以字符串格式存储的数据的类型,请问该如何检测文件中数据的类型?
现有数据处理函数
def inputData(txt, indexOfFile): # function that inputs data in the file print("*" * 10, "What do you want to do?", "*" * 10) print(" 1. Work with existing data \n 2. Add new data \n 3. Delete data \n 4. Go back") # printTxtFile() #function that prints txt file, but rn it doesnt even matter #list(data) = txt indexOfOperation = int(input()) #Выбор действия - работа с сущ данными - добавить новые данные - удалить данные - вернуться в главное меню some russian or something if(indexOfFile == 1): # based on user input it will open one of 3 files filePath = "buildings.txt" types = [0, 1, 1, 1] #array that declare which datatypes are in this file in each columns: 0 is string, 1 is int, 2 is float elif(indexOfFile == 2): filePath = "apartments.txt" types = [1, 1, 1, 1, 1, 1] elif(indexOfFile == 3): filePath = "apartment owners.txt" types = [1, 0, 0, 1, 1, 1] else: filePath = "buildings.txt" types = [0, 1, 1, 1] with open(filePath, "w", encoding="utf-8") as f: num_rows = len(txt) #number of columns num_columns = len(txt[0]) #number of rows (it's made strange, I know, but it is what it is) if indexOfOperation == 1: #this checks if we want to work with existing data print("Which row will you redact?") choise = int(input()) #entering number of the row printTxtFile(txt) #printing txt file for i in range(len(txt[choise - 1])): tmp = input("Enter your data: ").replace(' ', '_') #replacing spaces with underscores ok, k = check_type(tmp, types[i]) #ok checks if datatype was entered correctly, k is data while(not ok): #hard check print("Must be a number! Reenter!") tmp = input("Enter your data: ").replace(' ', '_') ok, k = check_type(tmp, types[i]) txt[choise][i] = k #entering data in the array for i in range(num_rows): #entering data from array to txt file for j in range(num_columns): f.writelines(str(txt[i][j]) + " ") if i != num_rows -1: f.writelines("\n") f.close()
类型检查辅助函数
def str_to_int(s): try: k = int(s) except ValueError: ok = False k = 0 #print('ValueError: не удалось преобразовать строку в float: ') else: ok = True #print('Успех, нет ошибок!') return ok, k def str_to_float(s): try: k = float(s) except ValueError: ok = False k = 0 #print('ValueError: не удалось преобразовать строку в float: ') else: ok = True #print('Успех, нет ошибок!') return ok, k # 0 -str 1-int 2-float def check_type(s, tp): k = 0 ok = True if (tp == 0): return True, s if (tp == 1): return str_to_int(s) if (tp == 2): return str_to_float(s)
解决方案
情况1:已知每列的类型(复用现有逻辑)
你代码里已经定义了每个文件对应的列类型types数组,导入文件数据时,直接按列类型调用check_type函数转换即可。写一个加载文件的函数:
def load_file(file_path, types): data = [] with open(file_path, encoding="utf-8") as f: for line in f: # 分割每行数据,过滤空字符串 row_str = [item.strip() for item in line.strip().split(' ') if item.strip()] row_converted = [] for idx, s in enumerate(row_str): # 按预设列类型转换数据 ok, val = check_type(s, types[idx]) # 转换失败时可选择保留原字符串或自定义处理 row_converted.append(val if ok else s) data.append(row_converted) return data
调用示例:
# 加载buildings.txt,使用对应列类型 buildings_data = load_file("buildings.txt", [0, 1, 1, 1])
情况2:未知列类型,自动检测
如果不清楚每列的预期类型,可以写自动检测逻辑:优先尝试转int,失败则转float,都不行就保留原字符串:
def auto_detect_type(s): # 先尝试转换为int ok, val = str_to_int(s) if ok: return val # 再尝试转换为float ok, val = str_to_float(s) if ok: return val # 都失败返回原字符串 return s # 自动检测类型加载文件 def load_file_auto_detect(file_path): data = [] with open(file_path, encoding="utf-8") as f: for line in f: row_str = [item.strip() for item in line.strip().split(' ') if item.strip()] row_converted = [auto_detect_type(item) for item in row_str] data.append(row_converted) return data
额外注意事项
- 你代码里
num_rows和num_columns的注释写反了,len(txt)是行数,len(txt[0])是列数,建议修正避免混淆。 - 分割数据时用
split(' ')可能因空格数量不一致出错,改用split()(默认分割任意空白字符)会更稳妥。
内容的提问来源于stack exchange,提问作者21DP1EShak
相关产品推荐
相关产品推荐

