修改程序以从文件中读取字典项并将反向字典写入文件

2024-06-25 23:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直用这个密码把头伸到墙上。生成的文件为空。你能检查一下我的代码并告诉我我可能做错了什么吗

我的文档中保存了一个简单的文本,如下所示:

加西亚,BCS,女,21岁 格泽奇尼克,工商管理学士,男,30岁 Kerrou,BCS,男,二十九岁 Saiki,BSA,男性,21岁 卡戴珊,AAS,女,21岁 杰克逊,AAS,女,25岁

我下面的代码实际上生成了一个新文件,但该文件不包含反向字典,它只返回一个空白文件

我感谢你们的帮助

# opening the input file
f1 = open('C:\\Users\\Dr. Younes\\OneDrive\\Documents\\student_profiles.txt', 'r')

# Initializing the original dictionary
list_dict = {}

for line in f1:
    line_items = line.strip().split(',')   # Splitting the line into elements by comma

    if line_items[0] in list_dict:       # Writing to dictionary if key is already present
        list_dict[line_items[0]].append(line_items[1])
        list_dict[line_items[0]].append(line_items[2])
        list_dict[line_items[0]].append(line_items[3])

    else:                        # Writing to dictionary if key is not present
    list_dict[line_items[0]] = [line_items[1], line_items[2], line_items[3]]

# Closing the input file as good practice
f1.close()

# Printing the original dictionary
print("Original")
for k, v in list_dict.items():
   print("{}: {}".format(k, v))
print("")

# Reading the each key in original dictionary
def invert_dict(d):
    inverse = dict()
    for key in d:            # reading each value in values of that key
        val = d[key]
        for element in val:
            if element not in inverse:
                inverse[element] = [key]     # Writing to inverted dictionary if key is not present

            else:
                inverse[element].append(key)  # Appending to inverted dictionary if key is present
    return inverse

# Making the inverted dictionary by calling the functions
inverseDict = invert_dict(list_dict)

# Printing inverted dictionary
print("Inverted")

for k, v in inverseDict.items():
    print("{}: {}".format(k, v))

# opening the my_inverted_dict.txt file in write mode
f2 = open('my_inverted_dict.txt', 'w')

# Writing one line at a time
for i in inverseDict:
    line = i + ',' + ','.join(inverseDict[i])
    f2.write(line)
    f2.write('\n')

# Closing the file as good practice
f2.close()

Tags: 文件thekeyinfordictionaryifline
1条回答
网友
1楼 · 发布于 2024-06-25 23:29:38

固定了第16行的压痕:

# opening the input file
f1 = open('test.txt', 'r')

# Initializing the original dictionary
list_dict = {}

for line in f1:
    line_items = line.strip().split(',')   # Splitting the line into elements by comma

    if line_items[0] in list_dict:       # Writing to dictionary if key is already present
        list_dict[line_items[0]].append(line_items[1])
        list_dict[line_items[0]].append(line_items[2])
        list_dict[line_items[0]].append(line_items[3])

    else:                        # Writing to dictionary if key is not present
        list_dict[line_items[0]] = [line_items[1], line_items[2], line_items[3]]

# Closing the input file as good practice
f1.close()

# Printing the original dictionary
print("Original")
for k, v in list_dict.items():
   print("{}: {}".format(k, v))
print("")

# Reading the each key in original dictionary
def invert_dict(d):
    inverse = dict()
    for key in d:            # reading each value in values of that key
        val = d[key]
        for element in val:
            if element not in inverse:
                inverse[element] = [key]     # Writing to inverted dictionary if key is not present

            else:
                inverse[element].append(key)  # Appending to inverted dictionary if key is present
    return inverse

# Making the inverted dictionary by calling the functions
inverseDict = invert_dict(list_dict)

# Printing inverted dictionary
print("Inverted")

for k, v in inverseDict.items():
    print("{}: {}".format(k, v))

# opening the my_inverted_dict.txt file in write mode
f2 = open('my_inverted_dict.txt', 'w')

# Writing one line at a time
for i in inverseDict:
    line = i + ',' + ','.join(inverseDict[i])
    f2.write(line)
    f2.write('\n')

# Closing the file as good practice
f2.close()

已创建包含以下内容的文本文件:

Garcia,BCS,female,twentyone Grzechnik,BBA,male,thirty Kerrou,BCS,male,twentynine
Saiki,BSA,male,twentyone Kardashian,AAS,female,twentyone Jackson,AAS,female,twentyfive

运行脚本并在输出文件中获得以下内容:

BCS,Garcia
female,Garcia
twentyone Grzechnik,Garcia
BSA,Saiki
male,Saiki
twentyone Kardashian,Saiki

相关问题 更多 >