【问题标题】:How do i return the position of a word that appears twice in a string?如何返回在字符串中出现两次的单词的位置?
【发布时间】:2017-01-06 22:23:42
【问题描述】:

我正在编写一个程序,用户必须输入一组字符串字符。然后他们选择一个可能在字符串中也可能不在字符串中的关键字。如果是,那么程序将遍历字符串并查看关键字出现了多少次,并将其打印到屏幕上。我已经这样做了,但是如果关键字出现两次。我如何得到它,如果这个词出现两次,那么程序将打印它的所有位置?

这是我目前所拥有的:

#Start by making a string
String = input("Please enter a set of string characters.\n")

#Make the user choose a keyword
Keyword = input("Please enter a keyword that we can tell you the position of.\n")

#Split the string into single words assigning the position to the word after the space
IndivualWords = String.split(' ')

#Start an IF statement 
if Keyword in IndivualWords:

    #If the IF is true then access the index and assign the keyword a position 
    pos = IndivualWords.index(Keyword)

    #Print the position of the word
    print (pos +1)

else:

    #Print an error
    print("That word is not in the string.")

【问题讨论】:

标签: python string


【解决方案1】:

在一个例子中使用enumerate(),其中“een”是关键字,line 是输入:

keyword = "een"
line = "een aap op een fiets"
for index, word in enumerate(line.split()):
    if word == keyword:
        print(index)

【讨论】:

  • 不打印位置,只打印单词索引。
  • @vz0 看看这个问题,这就是 OP 正在寻找的。​​span>
  • 他打印的是字符索引,而不是单词索引。在您的示例中,您打印 0、3,而他想打印 0、11。
  • @vz0 在 OP 的代码中,IndivualWords 是一个单词的列表,而不是一个字符串。所以,IndivualWords.index(Keyword) 返回的是单词列表的索引,而不是字符串的索引。
【解决方案2】:

您可以使用re.finditer,这是您的示例中的一个小示例:

import re

sentence = input("Enter a set of string characters:")
keyword = input("Enter a keyword that we can tell you the position of:")

for m in re.finditer(keyword, sentence):
    print('{0} found {1}-{2}'.format(keyword, m.start(), m.end()))

【讨论】:

    【解决方案3】:

    您可以使用正则表达式方法finditer()

    >>> keyword = 'fox'
    >>> s = 'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'
    
    >>> from re import finditer
    >>> print [match.start(0) for match in finditer(keyword, s)]
    [16, 61]
    

    或者如果您需要子字符串的范围:

    >>> print [(match.start(0), match.end(0)) for match in re.finditer(keyword, s)]
    [(16, 19), (61, 64)]
    

    【讨论】:

      【解决方案4】:

      如您所见,index 方法只返回第一个匹配项:

      >>> words = 'This is the time that the clock strikes'.split()
      >>> words.index('the')
      2
      

      此列表推导将返回所有匹配项的位置:

      >>> [i for i, word in enumerate(words) if word == 'the']
      [2, 5]
      

      如果你想为所有单词计算列表并格式化:

      >>> print('\n'.join('%-7s: %s' % (w, ' '.join(str(i) for i, word in enumerate(words) if word == w)) for w in words))
      This   : 0
      is     : 1
      the    : 2 5
      time   : 3
      that   : 4
      the    : 2 5
      clock  : 6
      strikes: 7
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-02
        • 1970-01-01
        • 2022-01-09
        • 2015-08-05
        • 1970-01-01
        相关资源
        最近更新 更多