2017-03-31 65 views
0

我正在做的任务是开发一个程序,用于识别句子中的单个单词,将它们存储在一个列表中,并用该单词在列表中的位置替换原始句子中的每个单词。为什么我不能在这段代码上使用break,我可以使用什么呢? python

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,但这对我来说并不奏效,因为我无法将文字输入到文件中。

我是这个网站的新手,但我一直在追踪很长一段时间。希望这是对的,如果我说错了话,我会接受批评。

+1

移动'打印(句子)'和'字=输入(“你噜...'外循环的什么字 –

+0

斯蒂芬·劳赫如果我这样做,然后我得到。这句话打印了6次,但它确实与我需要它做的一起工作,我如何避免句子被打印6次? – hana

+0

您是否将循环外的“打印(句子)”移动了? –

回答

0

您在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") 
相关问题