Python中TSV文件转字典列表格式异常,如何修正?
TSV转字典列表的问题排查与修复
问题场景
用户有一份结构如下的TSV文件:
date fruit weight unit 2021-10-07 avocado 150 g 2021-10-17 mango 300 g 2021-10-29 banana 90 g 2021-11-28 avocado 100 g 2021-12-02 avocado 120 g 2021-12-04 orange 92 g
期望转换为如下格式的字典列表:
{'date': '2021-10-07', 'fruit': 'avocado', 'weight': '150', 'unit': 'g'}, {'date': '2021-10-17', 'fruit': 'mango', 'weight': '300', 'unit': 'g'}, ...
用户使用以下Python代码处理:
import pandas as pd import os def load_tsv_file(file_name): file_location = f"data/{file_name}" if not os.path.isfile(file_location): raise FileNotFoundError(f"The file '{file_location}' does not exist.") try: data = pd.read_csv(file_location, sep='\t') return data except pd.errors.EmptyDataError as e: raise ValueError(f"The file '{file_location}' is empty.") from e except pd.errors.ParserError as e: raise ValueError(f"Error parsing the TSV file '{file_location}'. Please check the file format.") from e yield_data = load_tsv_file('fruit_weight.tsv') fruit_data_dict = fruit_data.to_dict('records') for item in fruit_data_dict: print(item)
但得到的结果是每个字典仅包含一个合并的键值对:
{'date fruit weight unit': '2021-10-07 avocado 150 g'} {'date fruit weight unit': '2021-10-17 mango 300 g'} {'date fruit weight unit': '2021-10-29 banana 90 g'} {'date fruit weight unit': '2021-11-28 avocado 100 g'} {'date fruit weight unit': '2021-12-02 avocado 120 g'} {'date fruit weight unit': '2021-12-04 brocolli 92 g'}
问题原因
- 分隔符不匹配:从输出结果可判断,文件实际用多个连续空格分隔列,而非TSV标准的制表符(
\t)。用户指定sep='\t'后,pandas无法正确拆分列,将整行内容识别为单个字段。 - 变量名错误:代码中
yield_data = load_tsv_file(...)定义了变量,但后续调用fruit_data.to_dict('records')时使用了未定义的fruit_data,这会直接触发NameError(推测用户实际运行时临时修正了变量名,但未解决核心的分隔符问题)。
修复方案
方案一:适配空格分隔的文件
如果文件确实是用空白字符分隔,修改pd.read_csv的参数,用正则表达式\s+匹配任意数量的空白字符(包含空格、制表符),同时指定engine='python'避免正则分隔符的兼容性警告:
import pandas as pd import os def load_tsv_file(file_name): file_location = f"data/{file_name}" if not os.path.isfile(file_location): raise FileNotFoundError(f"The file '{file_location}' does not exist.") try: # 用\s+匹配任意空白字符,engine='python'支持正则分隔符 data = pd.read_csv(file_location, sep='\s+', engine='python') return data except pd.errors.EmptyDataError as e: raise ValueError(f"The file '{file_location}' is empty.") from e except pd.errors.ParserError as e: raise ValueError(f"Error parsing the file '{file_location}'. Please check the file format.") from e # 修正变量名,保持前后一致 fruit_data = load_tsv_file('fruit_weight.tsv') fruit_data_dict = fruit_data.to_dict('records') for item in fruit_data_dict: print(item)
方案二:转换为标准TSV格式
若要严格遵循TSV规范,可通过文本编辑器的替换功能,将文件中的所有连续空格替换为单个制表符,之后保持sep='\t'参数即可正常解析。
预期运行结果
修正后将输出符合要求的字典列表:
{'date': '2021-10-07', 'fruit': 'avocado', 'weight': 150, 'unit': 'g'} {'date': '2021-10-17', 'fruit': 'mango', 'weight': 300, 'unit': 'g'} {'date': '2021-10-29', 'fruit': 'banana', 'weight': 90, 'unit': 'g'} {'date': '2021-11-28', 'fruit': 'avocado', 'weight': 100, 'unit': 'g'} {'date': '2021-12-02', 'fruit': 'avocado', 'weight': 120, 'unit': 'g'} {'date': '2021-12-04', 'fruit': 'orange', 'weight': 92, 'unit': 'g'}
内容的提问来源于stack exchange,提问作者Lili
相关产品推荐
相关产品推荐

