2016-04-10 16 views
-1

私のコードには圧縮された文章が含まれているファイル "filefile.txt"があります。ファイルは次のように配置されています:私が作成したファイルを解凍しようとしています

1 
2 
3 
4 
5 
1 
2 
6 
9 
10 
11 
2 
12 
12 
9 

This 
is 
a 
sentence 
. 
too 
! 
Yo 
yo 
bling 

解凍したい元のテキストに「!」と書かれています。

私のコードは言う:これは誤りである

fo = open("filefile.txt","r") 
script = fo.readline() 
script2 = fo.readline() 
fo.close() 
script2 = script2.split() 
script = [s.strip("\n") for s in script] 

sentencewords = [] 

while len(script) > 0: 
    for p in script: 
     sentencewords.append(enumerate(script2.index(p))) 
     script.remove(0) 

print(sentencewords) 

:私は含まれてsentencewordsが必要

Traceback (most recent call last): 
    File "F:\code attempts\AT13.py", line 46, in <module> 
    sentencewords.append(enumerate(script2.index(p))) 
ValueError: '1' is not in list 

"これは文であるこれは、あまりにもあるヨーヨーケバケバしい!"

今変更しましたが、まだ動作しません。 sentencewords.append((script2.enumerate(P))を列挙する)

'Traceback (most recent call last): 

ファイル: sentencewords.appendに、ライン46 "F \コード\ AT13.pyを試みる"(((script2.enumerateを列挙するp))) AttributeError: 'list'オブジェクトに '列挙型'属性がありません。

この問題を回避する別の方法があるか、現在のコードを修正する方法があるか知っていますか?

fo = open("filefile.txt","r") 
script = fo.readline() 
script2 = fo.readline() 
fo.close() 
script2 = script2.split() 
script = [s.strip("\n") for s in script] 

sentencewords = [] 

indexes = [] 
for line in fo: 
    if line.strip().isdigit(): 
     indexes.append(line) 
    else: 
     break 


words = [line.strip() for line in fo if line.strip()] 

while len(script) > 0: 
    for p in script: 
     sentencewords.append(words[index-1]) 


print(sentencewords) 

コードは更新されましたが、Pythonの最新の出力でI/Oが何を意味するのか分かりません。

Traceback (most recent call last): 
    File "F:/code attempts/attempt14.py", line 45, in <module> 
    for line in fo: 
ValueError: I/O operation on closed file. 

fo.closeは()のコードのさらに下に移動されている今では私のコードを修正する方法について

Traceback (most recent call last): 
File "F:\code attempts\attempt14.py", line 55, in <module> 
sentencewords.append(words[index-1]) 
MemoryError 

任意の提案を言い、私は

感謝に感謝するだろう

+1

ループする前にすでにファイル "fo"を閉じているため、このエラーが発生します。 – TheLazyScripter

+0

........ありがとうございました...... –

答えて

0

より良い方法でテキストファイルを書式設定すると、扱いやすくなります。あなたはその多くの言葉を持っていないので、10以上の

1 2 3 4 5 1 2 6 9 10 11 2 12 12 9 
This is a sentence. too ! Yo yo bling 

そして、これを行う...

script = [] 
sentencewords = [] 
with open("filefile.txt", "r") as fo: 
    for line in fo: 
     script.append(line.strip("\n").split(" ")) 
    for i in script[0]: 
     sentencewords.append(script[1][int(i)-1]) 
print(sentencewords) 

あなたの指数は、しかし問題を提供します。

関連する問題