将列表转换为字符串,然后在字符串中查找单词的位置

时间:2016-09-22 16:58:59

标签: python

代码:(Python 3.5.2)

import time
import sys


def Word_Position_Finder():
    Chosen_Sentence = input("Make a simple sentence: ")
    Sentence_List = Chosen_Sentence.split()
    if len(Chosen_Sentence) == 0:
        print("Your Sentence has no words! Restarting Program.")
        time.sleep(1)
        Restarting_Program()        
    print(Sentence_List)
    time.sleep(1)
    Users_Choice = input("Do you want to make a new sentence (press 1) or keep current sentence (press 2): ")
    if Users_Choice == "1":
        print("Restarting Program.")
        time.sleep(1)
        Restarting_Program()           
    elif Users_Choice == "2":
        print(Chosen_Sentence + ". This is your sentence.")
        Chosen_Word = input("Which word in your sentence do you want to find the position of? ")
        for index, word in enumerate(Sentence_List):
            if(word == Chosen_Word):
                print("Your word appears in the number " + str(index) + " slot of this sentence")  
        elif Chosen_Word not in Users_Sentence:
            print("That word isn't in the sentence")
            Choose_To_Restart()
    else:
        print("Restarting Program.")
        time.sleep(1)
        Restarting_Program()

def Choose_To_Restart():
    time.sleep(1)
    loop = input("Want to try again, Y/N?")
    if loop.upper() == "Y" or loop.upper() == "YES":
        print("Restarting Program")
        time.sleep(1)
        Restarting_Program()
    elif loop.upper() == "N" or loop.upper() == "NO":
        print("Ending Program")
        time.sleep(1)
        sys.exit("Program Ended")  
    else:
        print("That isn't a valid answer, going to assume you said no.")
        time.sleep(1)
        sys.exit("Program Ended")


def Restarting_Program():
    Word_Position_Finder()


Word_Position_Finder()

问题:

  • 我遇到的问题是将用户列表转换为字符串然后打印并在打印用户所选单词的位置后出现问题。需要帮助的代码是在“此代码需要修复:”行之间;这显然不在实际代码中。

我正在编写用户输入句子的代码,然后该句子变成一个列表并显示给用户以决定他/她是否满意。在那之后(我遇到麻烦),用户在他们的句子中选择一个他们想要知道位置的单词,并且我必须打印所选单词的位置。我决定完全展示我的所有代码,这样任何阅读都可以帮助我改进(因为我喜欢编码,但我只是为学校任务做的)整体代码。

1 个答案:

答案 0 :(得分:1)

这是怎么回事?

    words_list = Users_Sentence.split()
    for index, word in enumerate(words_list):
        if(word == Chosen_Word):
            print("Your word appears in the number " + str(index) + " slot of this sentence")

这是一些控制台输出,用于显示split和enumerate正在执行的操作:

    >>> a="This is an example sentence"
    >>> words = a.split()
    >>> print(words)
    ['This', 'is', 'an', 'example', 'sentence']
    >>> for i, word in enumerate(words):
    ...     print(i)
    ...     print(word)
    ...
    0
   This
   1
   is
   2
   an
   3
   example
   4
   sentence