【问题标题】:Modifying a program to read dictionary items from a file and write the inverted dictionary to a file修改程序以从文件中读取字典项并将倒排字典写入文件
【发布时间】:2021-01-07 23:46:04
【问题描述】:

我一直在用这个代码在墙壁上抽头。生成的文件是空的。你能检查我的代码并告诉我我可能做错了什么吗?

我有一个简单的文本保存在我的文档中:

加西亚,BCS,女,二十一 Grzechnik,BBA,男,三十 克柔,BCS,男,二十九 Saiki,BSA,男,二十一岁 卡戴珊,AAS,女,二十一 杰克逊,AAS,女,二十五

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

感谢你们的帮助!

# 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()

【问题讨论】:

  • 您是否尝试过通过调试器运行?打印一些中间步骤?有什么事吗?
  • 实际上我还没有尝试通过调试器运行
  • 您应该始终在询问之前这样做。养成在浪费他人宝贵时间之前用尽所有可用途径的习惯。
  • 我收到此错误:回溯(最近一次通话最后一次):文件“C:\Users\Dr. Younes\OneDrive\Documents\my_program.py”,第 16 行,在 list_dict[ line_items[0]] = [line_items[1], line_items[2], line_items[3]] IndexError: list index out of range
  • 谢谢 burkay,我现在就试试

标签: python file dictionary


【解决方案1】:

修复了第 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

【讨论】:

猜你喜欢
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2013-01-23
相关资源
最近更新 更多