如何用Python JSON模块还原字符串格式的元组列表为原类型
解决字符串格式元组列表还原问题(使用JSON模块)
你遇到的问题很典型:从文件读出的Python元组列表是字符串格式,但JSON语法和Python字面量语法存在差异,直接用json.loads()就会触发解码错误。咱们一步步来搞定它:
问题根源
你的字符串是Python风格的字面量,但JSON对语法有严格要求,两者的冲突点在于:
- Python用单引号
'包裹字符串,而JSON要求必须用双引号" - Python支持元组
(),但JSON没有元组类型,只有数组[]
这些语法差异直接导致JSON解码器无法识别结构,抛出JSONDecodeError。
解决方案(基于JSON模块)
我们需要先把字符串转换成符合JSON规范的格式,再解析,最后转回元组列表:
import json # 你的原始字符串(实际使用时替换为从文件读取到的字符串即可) stli = "[('Rated 4.0', 'RATED\n A beautiful place to dine in.The interiors take you back to the Mughal era. The lightings are just perfect.We went there on the occasion of Christmas and so they had only limited items available. But the taste and service was not compromised at all.The only complaint is that the breads could have been better.Would surely like to come here again.'), ('Rated 4.0', 'RATED\n I was here for dinner with my family on a weekday. The restaurant was completely empty. Ambience is good with some good old hindi music. Seating arrangement are good too. We ordered masala papad, panner and baby corn starters, lemon and corrionder soup, butter roti, olive and chilli paratha. Food was fresh and good, service is good too. Good for family hangout.\nCheers'), ('Rated 2.0', 'RATED\n Its a restaurant near to Banashankari BDA. Me along with few of my office friends visited to have buffet but unfortunately they only provide veg buffet. On inquiring they said this place is mostly visited by vegetarians. Anyways we ordered ala carte items which took ages to come. Food was ok ok. Definitely not visiting anymore.')]" # 步骤1:将Python风格字面量转为JSON兼容格式 json_compatible_str = stli.replace("'", '"').replace("(", "[").replace(")", "]") # 步骤2:用JSON模块解析字符串 list_of_lists = json.loads(json_compatible_str) # 步骤3:将每个子列表转回元组,还原原始结构 tuple_list = [tuple(item) for item in list_of_lists] # 验证结果 print(tuple_list)
关键步骤解释
- 格式转换:通过字符串替换,把Python的单引号和元组括号转换成JSON认可的双引号和数组括号,让JSON解码器能正确识别数据结构。
- JSON解析:此时
json.loads()可以顺利解析字符串,得到一个列表的列表(因为JSON没有元组类型)。 - 转回元组:用列表推导式把每个子列表转回元组,完美还原你原本的元组列表结构。
特殊情况提示
如果你的评论内容里包含嵌套单引号(比如don't这种),直接全局替换单引号会出问题。这种情况下,需要先把内容里的单引号转义成\',再替换外层的单引号为双引号。不过从你的示例来看,暂时不需要处理这种场景。
内容的提问来源于stack exchange,提问作者Himanshu Poddar
相关产品推荐
相关产品推荐

