我必须将文件压缩成单词列表和位置列表才能重新创建原始文件。我的程序还应该能够获取压缩文件并重新创建原始文件的全文,包括标点符号和大写字母。除了娱乐之外,我有一切正确的东西,使用地图功能,我的程序不能将我的位置列表转换为浮点数,因为'['是列表。如何使用'.join'函数将列表转换为float?
我的代码是:
text = open("speech.txt")
CharactersUnique = []
ListOfPositions = []
DownLine = False
while True:
line = text.readline()
if not line:
break
TwoList = line.split()
for word in TwoList:
if word not in CharactersUnique:
CharactersUnique.append(word)
ListOfPositions.append(CharactersUnique.index(word))
if not DownLine:
CharactersUnique.append("\n")
DownLine = True
ListOfPositions.append(CharactersUnique.index("\n"))
w = open("List_WordsPos.txt", "w")
for c in CharactersUnique:
w.write(c)
w.close()
x = open("List_WordsPos.txt", "a")
x.write(str(ListOfPositions))
x.close()
with open("List_WordsPos.txt", "r") as f:
NewWordsUnique = f.readline()
f.close()
h = open("List_WordsPos.txt", "r")
lines = h.readlines()
NewListOfPositions = lines[1]
NewListOfPositions = map(float, NewListOfPositions)
print("Recreated Text:\n")
recreation = " " .join(NewWordsUnique[pos] for pos in (NewListOfPositions))
print(recreation)
我得到的错误是:
Task 3 Code.py", line 42, in <genexpr>
recreation = " " .join(NewWordsUnique[pos] for pos in (NewListOfPositions))
ValueError: could not convert string to float: '['
我使用Python IDLE 3.5(32位)。有没有人有任何想法如何解决这个问题?
'NewListOfPositions'是一个'map'对象,将'lines [1]'中的每个字符都转换为一个float。当你尝试迭代它时,它会在到达不能转换为'float'的东西时出错。 'line [1]'显然包含了字符'[',它不能被转换为浮点数。 – khelwood
为什么你将值和位置写入文件并在之后立即再次读取它们?只需使用您的原始数据!另外:你不能使用float作为列表的索引。 – Wombatz
有两件事情,第一个'VariableNamesLikeThis'通常是为Python中的类保留的,并且在你对问题的描述和你的代码之间存在不匹配:你说'单词和位置列表',但是你的代码试图将它分解为*字符*。 –