-1
我得到了一個任務,開發一個程序來標識句子中的單個單詞,將它們存儲在列表中,並將原始句子中的每個單詞替換爲該單詞在列表中的位置。我也做了代碼,但是當我運行它,我得到一個錯誤:試圖壓縮文本時出現ValueError
Traceback (most recent call last):
File line 11, in <module>
PositionOfWords = list2.index(word)
ValueError: Substring not found
這裏是我的代碼:
UserSentence = input("enter sentence:").lower()
words = UserSentence.split()
PositionOfWords = [words]
list1 = []
list2 = ""
for word in words:
if PositionOfWords not in list1:
list1.append(PositionOfWords)
for word in words:
PositionOfWords = list2.index(word)
list2+=string(PositionOfWords+int("1"))
list2 +=("")
list1str += ";".join(list)
file = open ("filename.txt","w")
file.write
file.write(sentence)
file.write(list1str)
file.write(list2)
file = open ("filename.txt", "r")
print (file.read())
file.close
錯誤不明顯。 'list2'是空的,所以你不能得到任何單詞的任何索引。你真的自己寫這個嗎? – linusg
是的,我做的事情是我不是一個好程序員謝謝 –
'.index'檢索列表中的元素的索引(或字符串,但你試圖使用它,就好像目標是一個列表),而你的'list2'是空的:'list2 =「」'。你確定你不是指'list1.index(word)'嗎? –