2016-12-04 4 views
0

私はPythonの全般的な騒ぎで、自分のコードで助けが必要です。 このコードは、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) 

あなたはちょうどあなたがforwhileの用途を誤解している次のこの

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

を行うことができます。

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

ありがとうございます!私はあなたのおかげでそれを理解することができました。 –

関連する問題