0

我正在尝试上 Python 课程,但发现讲师将其留给谷歌来教我们。我必须读取两个文本文件,解析它们,并将数据存储在字典中,以便将其用于比较和打印两个文本文件的结果。既然您知道我为什么要尝试做某事,那么我要做的就是打印一个数据列表,使其看起来对人眼可读。目前在打印时,我收到如下列表:

{0: ('Arthur', '3', '1'), 1: ('Lancelot', '0', '0'), 2: ('Robin', '0', '2'), 3: ('Arthur', '0', '3'), 4: ('Lancelot', '2', '0'), 5: ('Robin', '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

任何帮助,将不胜感激。我似乎从谷歌或其他人那里学到的东西比我在课堂上学到的更多,令人沮丧。

4

2 回答 2

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')}
于 2013-01-21T22:07:52.970 回答
0

帕维尔关于印刷的说法是正确的。不过,您的解析对我来说似乎过于复杂,所以我将投入 2 美分:

>>> 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产生 ( )。每行的值是 a ,这是每行拆分的值由.index, valuetuple;

当然,一开始可能看起来有点令人生畏,但是一旦你真正了解了如何使用 Python 的 stdlib,阅读这样的表达式几乎成为第二天性。

于 2013-01-21T22:46:31.140 回答