我一直用这个密码把头伸到墙上。生成的文件为空。你能检查一下我的代码并告诉我我可能做错了什么吗
我的文档中保存了一个简单的文本,如下所示:
加西亚,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()
固定了第16行的压痕:
已创建包含以下内容的文本文件:
运行脚本并在输出文件中获得以下内容:
相关问题 更多 >
编程相关推荐