循环读取文件提取数据无法生成正确的值列表问题排查
问题根因
- 变量作用域错误:外层遍历文件所有行的for循环结束后,
row变量只会保留文件最后一行的内容。后续遍历拆分后的数据判断为整数时,你执行的是integers.extend(row.split(",")),把最后一行的拆分结果重复加入整数列表,而不是把当前匹配到的整数值values加入列表,这是你看到重复最后一行值的核心原因。 - 类型判断逻辑错误:
isnumeric()仅能识别无符号的纯数字字符串,负整数、带千分符的整数都无法识别;- 你没有区分小数、带空格的短语/句子的逻辑,类似
Address unknown这类带空格的内容会被你误判定为float。
- 缺少其余三类数据的存储列表,不符合你要分别存储四类数据的需求。
修复后代码
def data_reading(): # 初始化四类数据存储列表 integers = [] floats = [] single_words = [] sentences = [] with open("my_lines.txt", "r", encoding="utf-8") as file: # 逐行处理 for row in file: row = row.strip() if not row: continue # 按逗号拆分,去除每个元素前后空格 items = [item.strip() for item in row.split(",")] for item in items: # 先判断是不是数字类型 # 优先判断整数 try: int(item) integers.append(item) print(f"{item} - integer") continue except ValueError: pass # 再判断小数 try: float(item) floats.append(item) print(f"{item} - float") continue except ValueError: pass # 非数字内容判断是单个单词还是句子 if " " in item: sentences.append(item) print(f"{item} - sentence") else: single_words.append(item) print(f"{item} - single word") # 返回四个列表供写入调用 return integers, floats, single_words, sentences # 调用读取函数 integers, floats, single_words, sentences = data_reading() # 写入文件工具函数 def write_to_file(data_list, file_path): with open(file_path, "w", encoding="utf-8") as f: for item in data_list: f.write(f"{item}\n") # 分别写入对应文件 write_to_file(integers, "integers.txt") write_to_file(floats, "floats.txt") write_to_file(single_words, "single_words.txt") write_to_file(sentences, "sentences.txt")
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

