You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将特定格式的文本文件转换为Python字典?

解决方法

直接用正则表达式精准分割每行的坐标与文本内容,避免文本内的符号干扰,具体实现代码如下:

import re

result_dict = {}

# 读取文件并处理每行内容
with open("dico_objets.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        
        # 匹配坐标和文本部分
        match = re.match(r'^\((\d+),\s*(\d+)\),\s*(.*)$', line)
        if match:
            x = int(match.group(1))
            y = int(match.group(2))
            # 去除文本首尾的单/双引号
            text_content = match.group(3).strip('\'"')
            result_dict[(x, y)] = text_content

# 按目标格式输出字典
print("{")
for coord, content in result_dict.items():
    # 转义内容里的双引号,避免输出冲突
    escaped_content = content.replace('"', '\\"')
    print(f"    {coord}: \"{escaped_content}\",")
print("}")

代码说明

  • 用with语句打开文件,无需手动关闭,更安全可靠。
  • 正则表达式r'^\((\d+),\s*(\d+)\),\s*(.*)$':精准匹配开头的坐标格式,捕获x、y数值和后续的文本内容,完全规避文本内逗号或符号的干扰。
  • strip('\'"')统一去除文本首尾的单/双引号,兼容原文件里两种引号的写法。
  • 输出时转义内容中的双引号,确保生成的字典字符串格式合法。

内容的提问来源于stack exchange,提问作者user18129904

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:35:40