2017-03-02 34 views
-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 
+0

錯誤不明顯。 'list2'是空的,所以你不能得到任何單詞的任何索引。你真的自己寫這個嗎? – linusg

+0

是的,我做的事情是我不是一個好程序員謝謝 –

+0

'.index'檢索列表中的元素的索引(或字符串,但你試圖使用它,就好像目標是一個列表),而你的'list2'是空的:'list2 =「」'。你確定你不是指'list1.index(word)'嗎? –

回答

0

好了 - 這樣,而不是固定的代碼,我冒昧地重新-寫下來。 希望我的邏輯正確。

此外,請不要使用文件作爲變量,作爲其內置的變量在Python中。這會造成問題,也不是一個好的做法。

這裏是高層次的僞代碼

  • 讀取用戶輸入

  • 轉換爲UserSentence列出的字符串

  • 閱讀列表,並追加到從輸入句子獨特的單詞列表 as PositionOfWords
  • 現在檢查用戶輸入的字符串列表並構造一個字符串 newSentence從PositionOfWords
  • 其索引位置
  • 寫UserSentence到文件
  • 寫PositionOfWords到文件
  • 寫newSentence到文件

這裏的工作代碼:

UserSentence = input("enter sentence:").lower().split() 
#list to store unique words 
PositionOfWords = [] 

newSentence = '' #new sentence 


#Read each word in UserSentence and process 
for word in UserSentence: 
    if word not in PositionOfWords: 
     PositionOfWords.append(word) 

#Once we have unique words list, Lets get their positions in given sentence 
for word in UserSentence: 
    #get position of word append to new sentence 
    newSentence += str(PositionOfWords.index(word)) 

newSentence = ' '.join(newSentence) 

myfile = open ("filename.txt","w") 
myfile.writelines('UserSentence = {} '.format(UserSentence)) 
myfile.writelines('\n') 
myfile.writelines('PositionOfWords = {} '.format(PositionOfWords)) 
myfile.writelines('\n') 
myfile.writelines('newSentence = {} '.format(newSentence)) 
myfile.close() 

print PositionOfWords 
print newSentence 

文件輸出:

UserSentence = ['this', 'is', 'repeating', 'sentence', 'this', 'is', 'repeating', 'sentence']
PositionOfWords = ['this', 'is', 'repeating', 'sentence']
newSentence = 0 1 2 3 0 1 2 3

相關問題