我正在尝试解压缩我创建的文件

2024-04-27 02:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有一个文件“文件.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:\code attempts\AT13.py", line 46, in <module>
    sentencewords.append(enumerate(script2.index(p)))
ValueError: '1' is not in list

我需要sentencewords包含“这是一个句子。这太可怕了!哟哟哟你知道吗

我现在改了,但还是不行。 sentencewords.append语句(枚举(script2.enumerate(p)))

'Traceback (most recent call last):

文件“F:\code attempts\AT13.py”,第46行,in sentencewords.append语句(枚举(script2.enumerate(p))) AttributeError:“list”对象没有“enumerate”属性

有没有人知道有没有其他方法来解决这个问题,或者如何修复我当前的代码?你知道吗

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.关闭()已经被移到代码的下面,现在它说

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

如果有任何关于如何修复我的代码的建议,我将不胜感激

谢谢


Tags: 文件代码inforreadlineindexlinescript
1条回答
网友
1楼 · 发布于 2024-04-27 02:27:26

以更好的方式格式化文本文件,这样会更容易处理。你知道吗

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)

你的指数超过10会给问题,虽然,因为你没有那么多的话。你知道吗

相关问题 更多 >