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

Python生成倒排字典时输出文件为空的问题求助

解决倒排字典输出为空的问题

你的输出文件为空,核心问题出在读取输入文件的逻辑完全不匹配文件格式,导致没有读到任何有效数据,后续的反转和写入自然无内容。

问题分析

你输入的maindictionary.txt是标准的Python字典格式,但你的read_dictionary函数错误地假设每行是key, value的简单格式,还加了line.count(',') != 1的判断——而你的文件里每行要么逗号远多于1个(列表行),要么没有逗号(大括号行),所以所有行都被跳过,最终main_dictionary是空字典。

另外,原invert_dictionary函数也有问题:原字典的value是列表(比如'Art'对应['Pocahontas', 'Jasmine', 'Tiana']),但你直接把整个列表当成了反转字典的key,这不符合倒排需求——我们需要把列表里的每个名字作为key,对应的学科作为value。

修正后的完整代码

import ast

# 文件路径
input_file = "/Python/maindictionary.txt"
output_file = "/Python/inverteddictionary.txt"

# 读取Python格式的字典文件
def read_dictionary(input_file):
    with open(input_file, 'r') as file:
        # 读取全部内容,用ast.literal_eval安全解析为字典(比eval更安全)
        content = file.read()
        main_dictionary = ast.literal_eval(content)
    return main_dictionary

# 正确反转字典:遍历每个学科下的名字,将名字映射到对应的学科列表
def invert_dictionary(main_dictionary):
    inverted_dictionary = {}
    for subject, names in main_dictionary.items():
        for name in names:
            if name not in inverted_dictionary:
                inverted_dictionary[name] = [subject]
            else:
                inverted_dictionary[name].append(subject)
    return inverted_dictionary

# 写入倒排字典到文件(用'w'模式覆盖,避免重复内容)
def write_inverted_dictionary(inverted_dictionary, output_file):
    with open(output_file, 'w') as file:
        for name, subjects in inverted_dictionary.items():
            file.write(f"{name}: {', '.join(subjects)}\n")

# 执行流程
main_dictionary = read_dictionary(input_file)
inverted_dictionary = invert_dictionary(main_dictionary)
write_inverted_dictionary(inverted_dictionary, output_file)

关键说明

  1. 读取文件:用ast.literal_eval()可以安全解析文件中的Python字典结构,不需要手动处理每行格式,这是处理这类文件的标准做法。
  2. 反转逻辑:必须遍历每个学科对应的名字列表,把每个名字作为新字典的key,将学科添加到对应的value列表中。
  3. 写入模式:用'w'模式代替'a',每次运行都会覆盖旧文件,避免多次运行后内容重复。
  4. 你的输入文件格式是正确的,不需要修改大括号或列表格式,之前的修改操作是多余的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:00:14