我正在做的任务是开发一个程序来识别句子中的单个单词,将它们存储在一个列表中,并用该单词在列表中的位置替换原始句子中的每个单词。
sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
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
word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
print(sentence)
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
elif question=="N":
print("The program will now close")
else:
print("you did not enter one of the prescribed letters")
words.write(word + " ")
position.write(positionofword + " ")
我的问题是我陷入了以下循环:
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
因此,这意味着我无法将这些词放入文件中。我曾尝试使用 break,但这对我不起作用,因为我无法将这些词放入文件中。
我是这个网站的新手,但我已经跟踪了一段时间。希望这是正确的,如果我措辞错误,我愿意听取批评。
您在 for 循环中的逻辑不正确 - 而不是询问用户想要查找的单词,而是询问句子中的每个单词,并且只有当他们输入他们想要的单词时才匹配当前正在检查的单词. 您还为句子中的每个单词打印了一次句子。像这样重构它:
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):
print("your word is in this position:", i+1)
positionofword=i+1
break
else:
print("This didn't work")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句