2016-08-30 64 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)] 
相關問題