我正在嘗試使用python類,並且發現教師正在將它留給Google來教導我們。我必須閱讀兩個文本文件,解析它們,並將數據存儲在字典中,以用於比較和打印兩個文本文件的結果。既然你知道我爲什麼要做點什麼,我想要做的就是打印一份數據列表,以便人眼可以看到它。目前,打印時我收到類似下面的列表:使用「打印」字典時的控制檯輸出格式
{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
任何幫助,將不勝感激。我似乎從谷歌或其他人那裏學到的東西比我在課堂上做得更多,令人沮喪。
的'家庭作業「標籤正在被刪除,請不要將其用於新問題。 –
您希望字典的打印輸出如何更好或比默認版本更具可讀性?據我所知,你所做的只是在元組之後刪除逗號。 ETA:現在我在你的帖子的原始文本中看到,你希望他們分開行。 Pavel的'pprint'的建議很棒 –