Python读取CSV文件遇嵌套字符串时如何提取内部整数数值?
问题根因
- CSV条目中的每个数值都被双引号包裹,按逗号拆分后得到的字符串为带前后引号的格式(例如
'"84424"'),包含非数字字符,直接调用int()会触发格式报错 - 原代码中
graph.append(source, target)语法错误,list.append()仅支持传入单个参数,需传入元组(source, target)才能正常存储成对的节点关系
解决方案
快速修复:手动剔除引号
对拆分后的字段调用strip('"')方法移除首尾的双引号后再转整数,修改后的代码如下:
graph = [] nodes = [] file = open(path) for line in file: # 拆分后批量移除首尾双引号 source, target = [item.strip('"') for item in line.split(',')] source_int = int(source) target_int = int(target) nodes.append(source_int) nodes.append(target_int) # 传入元组存储节点对 graph.append((source_int, target_int)) file.close()
更规范的方案:使用内置csv模块读取
Python标准库自带的csv模块会自动处理引号包裹、字段内逗号等标准CSV格式特性,不需要手动处理字符串拆分和引号剔除,兼容性和稳定性更高:
import csv graph = [] nodes = [] # with语法会自动处理文件关闭,避免资源泄露 with open(path, 'r', newline='') as f: reader = csv.reader(f) for row in reader: # csv.reader会自动去掉字段外层的双引号,直接得到数值字符串 source_int = int(row[0]) target_int = int(row[1]) nodes.append(source_int) nodes.append(target_int) graph.append((source_int, target_int))
内容的提问来源于stack exchange,提问作者Ishaan Raj MIshra
相关产品推荐
相关产品推荐

