Python如何将逗号分隔的txt文件或字符串转换为字典列表便于数据查询
Python 实现逗号分隔TXT内容转结构化字典列表方法
你示例中给出的目标结构为单条书籍的字典格式,我们最终会输出由多个这类字典组成的列表,完全适配后续按年份检索等需求,实现代码如下:
基础实现(处理字符串或普通TXT文件)
# 定义表头映射:原TXT表头 -> 目标字典key名 header_map = { "Title": "Name", "Author": "Author", "User Rating": "User Rating", "Reviews": "Reviews", "Price": "Price", "Publication Year": "Publication Year", "Genre(Fiction or nonfiction)": "Genre" } # 示例测试字符串 test_data = """ Title, Author, User Rating, Reviews, Price, Publication Year, Genre(Fiction or nonfiction) Girls,Hopscotch Girls,4.8,9737,7,2019,Non Fiction I - Alex Cross,James Patterson,4.6,1320,7,2009,Fiction If Animals Kissed Good Night,Ann Whitford Paul,4.8,16643,4,2019,Fiction """ # 处理字符串场景:拆分所有有效行,去除空白 lines = [line.strip() for line in test_data.strip().split("\n") if line.strip()] # 读取本地TXT文件场景,把上面一行替换为下方代码即可: # with open("你的文件路径.txt", "r", encoding="utf-8") as f: # lines = [line.strip() for line in f if line.strip()] # 转换表头为目标key格式 origin_headers = [h.strip() for h in lines[0].split(",")] target_headers = [header_map[h] for h in origin_headers] # 遍历数据行组装字典列表 book_list = [] for line in lines[1:]: fields = [f.strip() for f in line.split(",")] book_item = dict(zip(target_headers, fields)) book_list.append(book_item) # 输出验证结果 print(book_list)
输出结果格式如下:
[ {'Name': 'Girls','Author': 'Hopscotch Girls','User Rating':'4.8', 'Reviews':'9737', 'Price':'7', 'Publication Year':'2019', 'Genre':'Non Fiction'}, {'Name': 'I - Alex Cross','Author': 'James Patterson','User Rating':'4.6', 'Reviews':'1320', 'Price':'7', 'Publication Year':'2009', 'Genre':'Fiction'}, {'Name': 'If Animals Kissed Good Night','Author': 'Ann Whitford Paul','User Rating':'4.8', 'Reviews':'16643', 'Price':'4', 'Publication Year':'2019', 'Genre':'Fiction'} ]
后续检索示例(按年份查询)
# 接收用户输入年份,检索对应所有书籍 input_year = input("请输入要查询的出版年份:") filtered_books = [book for book in book_list if book["Publication Year"] == input_year] print(f"\n{input_year}年出版的书籍如下:") for book in filtered_books: print(f"书名:{book['Name']},作者:{book['Author']},评分:{book['User Rating']}")
优化方案(适配字段含逗号的场景)
如果你的数据中存在字段本身包含逗号的情况,建议使用Python内置的csv模块处理,避免拆分错误:
import csv header_map = { "Title": "Name", "Author": "Author", "User Rating": "User Rating", "Reviews": "Reviews", "Price": "Price", "Publication Year": "Publication Year", "Genre(Fiction or nonfiction)": "Genre" } book_list = [] with open("你的文件路径.txt", "r", encoding="utf-8") as f: reader = csv.reader(f) # 处理表头 origin_headers = [h.strip() for h in next(reader)] target_headers = [header_map[h] for h in origin_headers] # 处理数据行 for row in reader: if not row: continue fields = [f.strip() for f in row] book_list.append(dict(zip(target_headers, fields)))
内容的提问来源于stack exchange,提问作者the frog
相关产品推荐
相关产品推荐

