如何返回在字符串中出现两次的单词的位置?

时间:2016-08-30 14:51:51

标签: python string

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

这是我到目前为止所做的:

#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.")

4 个答案:

答案 0 :(得分:4)

在“een”是关键字的示例中使用enumerate()line输入:

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

答案 1 :(得分:1)

你可以使用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()))

答案 2 :(得分:1)

如您所见,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

答案 3 :(得分:1)

您可以使用正则表达式方法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)]