格式化字典的控制台输出使用“print”

0 投票
2 回答
3373 浏览
提问于 2025-04-17 13:19

我正在尝试学习Python编程,但发现老师把教我们这门课的责任留给了谷歌。我需要读取两个文本文件,解析它们,并把数据存储在一个字典里,以便进行比较并打印出两个文本文件的结果。现在你知道我为什么要做这些事情了,我具体想做的是把数据打印出来,让人看起来更容易理解。目前我打印出来的结果像这样:

{0: ('亚瑟', '3', '1'), 1: ('兰斯洛特', '0', '0'), 2: ('罗宾', '0', '2'), 3: ('亚瑟', '0', '3'), 4: ('兰斯洛特', '2', '0'), 5: ('罗宾', '1', '2'), ....

我希望在控制台中显示成这样,每一行只显示一个键值对,像这样:

  {0: ('Arthur', '3', '1')
   1: ('Lancelot', '0', '0')
   2: ('Robin', '0', '2')
   3: ('Arthur', '0', '3')
   4: ('Lancelot', '2', '0')
   5: ('Robin', '1', '2')
  ....}

我似乎不知道该问什么问题才能在谷歌上找到答案。显然,这应该是一个简单的格式化标志。这实际上不是作业的一部分,但我想学会怎么做,因为以后我还需要格式化程序的其他部分的输出。以下是我读取的文本文件作为输入:

Arthur;3;1
Lancelot;0;0
Robin;0;2
Arthur;0;3
Lancelot;2;0
Robin;1;2
Robin;2;1
Lancelot;1;1
Galahad;0;1
a random person;0;3
Arthur;1;1
Galahad;1;1
Galahad;3;0

注意:我不需要写出万无一失的代码,所以我没有这样做。我不需要考虑坏数据或任何类型的异常。我只需要处理这种类型的文本文件。

这是我的代码:

# readfile(string)
# Purpose: open a text file and iterate though the file, one line at a time.
# Input: string
# Returns: dictionary
def readResponses(filename):
    mapIndex = 0 # used to append to dictionary rows.
    for line in open(filename): # used to iterate through each txt file line.
        if mapIndex < 1:# assign key and tuple data.
            record = {mapIndex: parseForColon(line)} 
            mapIndex += 1
        elif mapIndex > 0: # append key and tuple data
            record.update({mapIndex: parseForColon(line)})
            mapIndex += 1   
    return record

#def readQuestions():


# parseForColon(string)
# Purpose: Parse string data to assign appropriate data to three variables. Slices an input string one char
# qt-a-time until a delimiter is found. Delimiters are disregarded and a tuple is packed into a single variable.
# Input: String - The next line of text
# Returns: a packed tuple
# Called by readResponses(string)
def parseForColon(line): # This function iterates, releases memory, and is called anew from parent function.
        string1, name, = line, "" # needed to receive text file line and slices of that string.
        length = len (line)
        count = 0
        while count < length: # slice the string one char at a time until a delimiter is found.
                if string1[count] == ';':
                        count += 1 # increment past the delimeter and assign next parameter.
                        question = string1[count]
                        count += 2 # increment past the next delimeter and assign last parameter.
                        answer = string1[count]
                        count += 1 #exceed length and break loop.
                        break
                elif string1[count] != ';': # while delimeter not encountered, append first parameter one char at-a-time.
                        name += string1[count]
                        count += 1
        data = name, question, answer
        return data #return tuple.

#parse answers text file and save data to a dictionary. 
answerMap = readResponses("responses.txt")
print answerMap

任何帮助都将不胜感激。我发现自己从谷歌或其他人那里学到的东西比在课堂上学到的要多,这让我感到沮丧。

2 个回答

0

Pavel说得对,关于打印的部分。不过,我觉得你的解析方法有点复杂,所以我想说说我的看法:

>>> from pprint import pprint
>>> s = """Arthur;3;1
... Lancelot;0;0
... Robin;0;2
... Arthur;0;3
... Lancelot;2;0
... Robin;1;2
... Robin;2;1
... Lancelot;1;1
... Galahad;0;1
... a random person;0;3
... Arthur;1;1
... Galahad;1;1
... Galahad;3;0"""
>>> pprint(dict([(n, tuple(l.split(';'))) for n, l in enumerate(s.split('\n'))]))

这就是你整个程序的核心,实际上只用一行代码(当然,你需要根据输入来调整,假设输入是一个单独的字符串)。

基本上,我们是在创建一个字典,这个字典的键是通过enumerate函数得到的索引(当你遍历一个列表时,它会返回一个index, value的元组)。每一行的值是一个tuple,这个元组是通过;把每一行的内容分开的。

当然,一开始看起来可能有点吓人,但一旦你真正理解了如何使用Python的标准库,像这样的表达式阅读起来几乎就变得很自然了。

3

这看起来很像 pprint 的格式化方式:

In [14]: x={0: ('Arthur', '3', '1'), 1: ('Lancelot', '0', '0'), 2: ('Robin', '0', '2'), 3: ('Arthur', '0', '3'), 4: ('Lancelot', '2', '0'), 5: ('Robin', '1', '2')}

In [15]: import pprint

In [16]: pprint.pprint(x)
{0: ('Arthur', '3', '1'),
 1: ('Lancelot', '0', '0'),
 2: ('Robin', '0', '2'),
 3: ('Arthur', '0', '3'),
 4: ('Lancelot', '2', '0'),
 5: ('Robin', '1', '2')}

撰写回答