【问题标题】:Find words in a sentence and its index position using a for loop使用 for 循环查找句子中的单词及其索引位置
【发布时间】:2017-06-22 15:53:20
【问题描述】:

我正在编写一个代码,提示用户输入一个定义为str1的句子,然后提示输入一个定义为str2的单词。

例如:

Please enter a sentence: i like to code in python and code things
Thank you, you entered:  i like to code in python and code things
Please enter a word: code

我想使用for 循环在str1 中查找str2 以打印是否找到该单词,如果已找到,则显示str2 的索引位置。

目前我有这个代码:

str1Input = input("Please enter a sentence: ")
print("Thank you, you entered: ",str1Input)

str1 = str1Input.split()

str2 = input("Please enter a word: ")

if str2 in str1:
    for str2 in str1:
        print("That word was found at index position", str1.index(str2)+1)
else:
    print("Sorry that word was not found")

虽然,结果似乎打印是否找到索引位置,但随后打印句子中每个单词的索引位置。此外,如果我正在搜索在该句子中出现两次的某个单词,它只会打印该单词在该句子中第一次出现的索引位置,例如:

Please enter a sentence: i like to code in python and code things
Please enter a word: code
Thank you, you entered:  i like to code in python and code things


That word was found at index position: 1
That word was found at index position: 2
That word was found at index position: 3
That word was found at index position: 4
That word was found at index position: 5
That word was found at index position: 6
That word was found at index position: 7
That word was found at index position: 4
That word was found at index position: 9

如果有人可以帮助我和其他尝试类似事情的人,那将非常有帮助!

【问题讨论】:

    标签: python string python-3.x for-loop indexing


    【解决方案1】:

    只需确保在 if/else 语句中使用比较并考虑您的循环在做什么。

    希望这足够简单但有效:

    编辑:添加一个计数器而不是使用“.index()”。保持良好和基本:

    str1In = "I like to code a few things and code a lot"
    str2 = "code"
    str1 = str1In.split()
    
    indexCount = 0
    for word in str1:
        if word == str2:
           print("Your word was found at index point",int(indexCount))
        else:
           print("Your word was not found at",int(indexCount))
        indexCount += 1
    

    【讨论】:

    • 这很好并且有效,尽管我的代码仍然会在单词第一次出现时打印它的索引位置。有什么方法可以让我坚持使用类似的方法来解决这个问题,因为您最初的答案非常简单且很有帮助:)
    • 我的坏家伙。我草率的编码!请参阅对帖子的编辑以添加索引点的计数器。 (每次循环重新开始时,它只会将计数加 1。对这个错误表示歉意!
    • 工作得非常好!谢谢老哥!
    • 不用担心,很高兴我能帮上忙。保持美观和简单!
    【解决方案2】:

    你可以做的是从 str1 中创建一个列表,然后找到 str2 在列表中出现的位置。代码如下:

       str1 = "i like to code in python and code things"
       str2 = "code"
    
      the_indexes = []
      the_new_list = [str1.split(' ')]
    
    
      the_count = str1.count(str2)
      if the_count > 0:
    
    
    
      for i in range(len(the_new_list[0])):
           if the_new_list[0][i] == str2:
               the_indexes.append(i)
    
      else:
          print str2, " not found in the first sentence"
    
      print "The indexes are: "
    
      for i in the_indexes:
           print i
    

    【讨论】:

      【解决方案3】:

      使用enumeratepython内置函数:

      for index, word in enumerate(splitted_sentence):
         if word == target_word:
             print("Index: ", index)
      

      文档:https://docs.python.org/3.3/library/functions.html#enumerate

      UPD: list.index() 方法返回匹配元素的最低索引。这就是为什么如果你的词在一个句子中出现两次,你总是得到相同的索引。

      也请查看相关文档:https://docs.python.org/3.6/tutorial/datastructures.html#more-on-lists

      【讨论】:

        【解决方案4】:

        您可以使用条件列表推导(类似于for-loop):

        >>> str1 = 'i like to code in python and code things'
        >>> str2 = 'code'
        
        >>> indices = [idx for idx, word in enumerate(str1Input.split(), 1) if word == str2]
        >>> indices
        [4, 8]
        

        为您提供匹配的索引。然后你可以对它们做任何你喜欢的事情:

        if indices:
            for idx in indices:
                print('word found at position {}'.format(idx)
        else:
            print('word not found')
        

        您的尝试实际上并不算太糟糕,但您犯了一个错误:for str2 in str1: 这会覆盖您的 str2 变量,该变量包含要查找的字符串!同样index 将始终为您提供变量的第一个索引,因此当您执行str1.index(str2)+1 时,您会寻找当前调查项目的第一次出现!这就是为什么你有两次That word was found at index position: 4,因为它只寻找第一个'code'

        文档总是有用的:

        list.index:

        返回列表中第一个值为 x 的项目的索引。如果没有这样的项目是错误的。

        【讨论】:

        • 你建议我如何解决“for循环”和“索引”函数,最好不要改变我的方法?
        • @LukeP_8 你能澄清一下“不改变我的方法”是什么意思吗?
        • 我的意思是通过坚持 for 循环等基本上保持我的代码相似。我不想为了更正它而对我的代码进行太多更改:)
        • 我认为在这种情况下other answer 会更好,或者您是否需要使用list.index
        【解决方案5】:

        您的问题出在for 循环中:每次迭代都将str1 中的值分配给本地 变量str1。它被称为可变阴影。 解决方法是在循环声明中使用不同的变量名。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-02-08
          • 1970-01-01
          • 2020-09-12
          • 2021-12-18
          • 2015-12-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多