2017-04-02 131 views
-1

我的代碼的目的是讓用戶輸入句子,請求一個位置,然後整個事情被讀取到一個/兩個文件,即位置和單詞。爲什麼我得到屬性錯誤?

sentencelist=[] #variable list for the sentences 
word=[] #variable list for the words 
positionofword=[] 
words= open("words.txt","w") 
position= open("position.txt","w") 
question=input("Do you want to enter a sentence? Answers are Y or N.").upper() 
if question=="Y": 
    sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read 
    sentencetext=sentence.isalpha or sentence.isspace() 
    while sentencetext==False: #if letters have not been entered 
     print("Only letters are allowed") #error message 
     sentence=input("Please enter a sentence").upper() #asks the question again 
     sentencetext=sentence.isalpha #checks if letters have been entered this time 

elif question=="N": 
    print("The program will now close") 

else: 
    print("please enter a letter") 


sentence_word = sentence.split(' ') 
for (i, check) in enumerate(word): #orders the words 
    print(sentence) 

sentence_words = sentence.split(' ') 
word = input("What word are you looking for?").upper() #asks what word they want 
for (i, check) in enumerate(sentence_words): #orders the words 
    if (check == word): 
     positionofword=print(str(("your word is in this position:", i+1))) 
     positionofword=i+1 
     break 
else: 
    print("This didn't work") 

words.write(word + " ") 
position.write(positionofword + " ") 

words.close() 
position.close() 

這是我的代碼,但我得到這個錯誤

position.write(positionofword + " ") 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

記住,這個詞文件是空的爲好。

+1

使用str()positionofword轉換爲字符串。你不能在一個int和一個字符串上使用'+'運算符 – Simon

+0

Simon所以我拿出'postionofword = i + 1'? – hana

回答

2

你代碼失敗在position.write(positionofword + " "),爲positionofword是整數," "是一個字符串,和Python不支持添加整數直接字符串。在for循環你`重新分配到positionofword` + 1,這使得它的整數

position.write(str(positionofword) + " ") 
+0

非常感謝你 – hana

1

錯誤在於python的解釋器首先讀取整數的類型,然後是+ " "部分。當解釋器試圖使用不支持添加字符串的整數加法函數時,這會產生一個錯誤。

你必須具體告訴python解釋器你想使用字符串加法(連接)函數。

position.write(str(positionofword) + " ") 
+0

非常感謝你。這讓我陷入了這麼長時間。 – hana

相關問題