我的代码的目的是让用户输入句子,询问位置然后将整个事物读取到一个/两个文件,即位置和单词。
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文件也是空的。
答案 0 :(得分:2)
您的代码在position.write(str(positionofword) + " ")
失败,因为position.write(positionofword + " ")
是一个整数,positionofword
是一个字符串,而python不支持直接向字符串添加整数。
使用" "
将str()
转换为字符串:
positionofword
答案 1 :(得分:1)
错误是python的解释器首先读取整数的类型,然后是query
部分。这会产生错误,因为解释器正在尝试使用不支持添加字符串的整数加法函数。
你必须具体告诉python解释器你想使用字符串加法(连接)函数。
+ " "