为什么我得到属性错误?

为什么我得到属性错误?

问题描述:

我的代码的目的是让用户输入句子,请求一个位置,然后整个事情被读取到一个/两个文件,即位置和单词。为什么我得到属性错误?

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

你代码失败在position.write(positionofword + " "),为positionofword是整数," "是一个字符串,和Python不支持添加整数直接字符串。在for循环你`重新分配到positionofword` + 1,这使得它的整数

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

非常感谢你 – hana

错误在于python的解释器首先读取整数的类型,然后是+ " "部分。当解释器试图使用不支持添加字符串的整数加法函数时,这会产生一个错误。

你必须具体告诉python解释器你想使用字符串加法(连接)函数。

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

非常感谢你。这让我陷入了这么长时间。 – hana