2016-08-30 66 views
0

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

这是我到目前为止有:

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

[字符串中的子串的基本索引复发(蟒蛇)](可能的重复http://stackoverflow.com/questions/ 6987702/basic-indexing-recurrings-of-a-substring-within-a-string-python) – FamousJameous

+0

http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an - 元素在列表中? –

+0

这可能有所帮助:https://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python @Chris_Rands这个问题并不是真的类似于这个虽然 – Dartmouth

回答

1

你可以使用re.finditer,这里有一个小例子你的例子:在例如使用enumerate()其中“EEN”是

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())) 
4

关键字line输入:

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

不打印位置,但单词索引。 – vz0

+0

@ vz0看着这个问题,这就是OP正在寻找的东西。 –

+0

他正在打印字符索引,而不是单词索引。在你的例子中,你打印0,3,他想打印0,11。 – vz0

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 
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)] 
相关问题