簡體   English   中英

為什么會出現屬性錯誤?

[英]why am i getting the attribute error?

我的代碼的目的是讓用戶輸入句子,要求一個位置,然后將整個內容讀取到一個/兩個文件中,即位置和單詞。

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'

請記住,word文件也是空的。

您的代碼在position.write(positionofword + " ")處失敗,因為positionofword是一個整數,而" "是一個字符串,並且python不支持將整數直接添加到字符串。

使用str()positionofword轉換為字符串:

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

錯誤是python的解釋器先讀取整數的類型,然后讀取+ " "部分。 由於解釋器嘗試使用不支持字符串加法的整數加法函數,因此會產生錯誤。

您必須明確告知python解釋器您要使用字符串加法(連接)功能。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM