2017-04-02 27 views
-1

私のコードの目的は、ユーザーが文章を入力し、位置を尋ね、次にすべてを1/2ファイル、すなわち位置と単語に読み込むことです。私のコードです属性エラーが表示されるのはなぜですか?

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

あなたのループのためにあなたがそれ整数になりれ、 'I + 1にpositionofword'を再割り当てしている中で:文字列にpositionofwordを変換する

使用str()。あなたはintと文字列で '+'演算子を使うことはできません – Simon

+0

Simonので、私は 'postionofword = i + 1'を取り出しますか? – hana

答えて

2

あなたのコードは、position.write(positionofword + " ")で失敗します。

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

ありがとう – hana

1

エラーは、pythonのインタープリタが最初にintergerの型を読み取ってから+ " "の部分を読み取っているというエラーです。インタプリタが文字列の追加をサポートしていない整数加算関数を使用しようとすると、エラーが発生します。

Pythonインタプリタに文字列追加(連結)機能を使用するように伝える必要があります。 positionofwordが整数であると" "が文字列で、Pythonは直接文字列に整数を追加サポートしていないよう

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

ありがとうございました。私はこのような長い間困惑していました。 – hana

関連する問題