2016-12-04 67 views
0

我是Python的完全noob,需要我的代碼的一些幫助。 該代碼旨在將Input.txt [http://pastebin.com/bMdjrqFE],將其拆分爲單獨的口袋妖怪(在列表中),然後將其拆分爲單獨的值,我使用它們來重新格式化數據並將其寫入Output.txt。當寫入文本文件時,列表中的值相同,不斷重複

但是,當我運行程序時,只有最後一個寵物小精靈被輸出,386次。 [http://pastebin.com/wkHzvvgE]

這裏是我的代碼:

f = open("Input.txt", "r")#opens the file (input.txt) 
nf = open("Output.txt", "w")#opens the file (output.txt) 
pokeData = [] 
for line in f: 
    #print "%r" % line 
    pokeData.append(line) 
num = 0 
tab = """ """ 
newl = """NEWL 
""" 
slash = "/" 
while num != 386: 
    current = pokeData 
    current.append(line) 
    print current[num] 
    for tab in current: 
     words = tab.split() 
     print words 
    for newl in words: 
     nf.write('%s:{num:%s,species:"%s",types:["%s","%s"],baseStats:{hp:%s,atk:%s,def:%s,spa:%s,spd:%s,spe:%s},abilities:{0:"%s"},{1:"%s"},heightm:%s,weightkg:%s,color:"Who cares",eggGroups:["%s"],["%s"]},\n' % (str(words[2]).lower(),str(words[1]),str(words[2]),str(words[3]),str(words[4]),str(words[5]),str(words[6]),str(words[7]),str(words[8]),str(words[9]),str(words[10]),str(words[12]).replace("_"," "),str(words[12]),str(words[14]),str(words[15]),str(words[16]),str(words[16]))) 
    num = num + 1 
nf.close() 
f.close() 

回答

1

有相當與您的程序開始與文件讀取的幾個問題。 要將文件的行讀入數組,可以使用file.readlines()。

所以不是

f = open("Input.txt", "r")#opens the file (input.txt) 
pokeData = [] 
for line in f: 
    #print "%r" % line 
    pokeData.append(line) 

你可以做這個

pokeData = open("Input.txt", "r").readlines() # This will return each line within an array. 

接下來會誤解的forwhile用途。

A for python循環被設計爲遍歷數組或列表,如下所示。我不知道for newl in words你想要做什麼,for循環會創建一個新變量,然後遍歷一個設置這個新變量值的數組。請參閱下文。

array = ["one", "two", "three"] 
for i in array: # i is created 
    print (i) 

輸出將是:

one 
two 
three 

所以爲了解決這個問題的很多,你可以整體更換,而像這樣的東西循環。

(下面的代碼是假設輸入文件已經被格式化,使得所有的文字,被標籤分開)

for line in pokeData: 
    words = line.split (tab) # Split the line by tabs 
    nf.write ('your very long and complicated string') 

其他傭工

你寫入到輸出文件看起來格式化字符串非常類似於JSON格式。有一個名爲json的內置python模塊,可以將本機python dict類型轉換爲json字符串。這可能會讓事情變得更加容易,但任何一種方式都有效。

希望這會有所幫助

+0

非常感謝!多虧了你,我才能弄明白。 –

相關問題