如何解压缩文件

时间:2016-04-10 11:09:59

标签: python

我的代码有一个文件" 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)

这是错误:

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

我需要sentencewords来包含&#34;这是一个句子。这也是!哟哟bling bling!&#34;

我现在已经改变它但它仍然无法正常工作。         sentencewords.append(枚举(script2.enumerate(P)))

'Traceback (most recent call last):

文件&#34; F:\计算代码尝试\ AT13.py&#34;,第46行,in     sentencewords.append(枚举(script2.enumerate(P))) AttributeError:&#39; list&#39;对象没有属性&#39;枚举&#39;

有没有人知道是否存在解决此问题的另一种方法或如何修复我当前的代码?

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:/Computing code attempts/attempt14.py", line 45, in <module>
    for line in fo:
ValueError: I/O operation on closed file.

有关如何修复代码的任何建议,我很感激

1 个答案:

答案 0 :(得分:0)

您的代码在文件关闭时使用文件解析:

fo.close()
...
indexes = []
for line in fo:

您可以将fo.close()延迟到脚本的末尾,它将通过ValueError: I/O operation on closed file.