2017-02-13 50 views
2

我一直试图弄清楚这一点,现在我只是无法弄清楚为什么我的代码只显示该单词的第一次使用。如果有人可以建议一个快速和简单的方法,它会显示两个,那将不胜感激。为什么.index只会选择重复单词的第一次使用

sentence = input("please insert a sentence").lower() 
keyword = input ("please insert a keyword you would like to search for") 
splitsentence = sentence.split(" ") 
position = sentence.index(keyword) 
if keyword in sentence: 
    print(position) 
+7

:生成指数发电机因为'index'函数就是这么做的。 –

+0

@Chris_Rands:这不是一个列表,而是一个字符串,它是一个*子字符串* ...但是可能在某处存在一个重复。 –

+0

@WillemVanOnsem你是对的,被愚弄,因为OP做了一个列表,但没有使用它,也许这个代替:http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string -within-A-字符串中的Python –

回答

1

这就是如何设计index();仅返回第一次出现。

如果你想查找所有的事件,你必须在循环或递归中多次调用它。我们这样做之前,你应该知道,你可以提供startend参数来定义在哪里的例句搜索:

>>> "cat cat".index("cat") 
0 
>>> "cat cat".index("cat", 1) # start search from index 1 
4 
>>> "cat cat".index("cat", 1, 4) # ...and stop search right before index 4 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: substring not found 

这样,我们才能避免在同一个索引所有的时间在我们的循环:

s = "cat cat" 
indexes = [] 

index = -1 
while True: 
    try: 
     index = s.index("cat", index + 1) 
    except ValueError: 
     break 
    indexes.append(index) 

print(indexes) 
# Output: [0, 4] 

这里是一个递归的生成,如果你想要去幻想:

def find_indices(s, sub, start=0, end=None): 
    if end is None: 
     end = len(s) 
    try: 
     start = s.index(sub, start, end) 
    except ValueError: 
     return 
    yield start 
    yield from find_all_indexes(s, sub, start + 1, end) 

使用(也仍然支持startend参数):

>>> list(find_indices("cat cat cat cat", "cat")) 
[0, 4, 8, 12] 

或者,如果你想有一个非递归生成器,你可以使用原来的while循环并将其yield,而不是追加到一个列表:

def find_indices(s, sub, start=0, end=None): 
    if end is None: 
     end = len(s) 
    start -= 1 
    while True: 
     try: 
      start = s.index(sub, start + 1, end) 
     except ValueError: 
      break 
     yield start 

完全一样用法如前。

0

因为那是.index是如何定义的:在documentation说:

str.index(sub[, start[, end]])

find(), 但提高ValueError时没有找到的子字符串。

.find

str.find(sub[, start[, end]])

返回的最低索引串在子子被发现 切片s[start:end]内。可选参数开始和结束为 解释为切片符号。如果找不到sub,返回-1

(高亮加)

一个主意,找所有指数是使用:

[i for i in range(len(sentence)) if keyword == sentence[i:i+len(keyword)]] 

或许更有效:

def find_indices(sentence,keyword): 
    idx = -1 
    while True: 
     idx = sentence.find(keyword,idx+1) 
     if idx < 0: 
      break 
     yield idx 
相关问题