繁体   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