2016-08-15 18 views
0
word = 'laugh'  
string = 'This is laughing laugh' 
index = string.find (word) 

索引是8,應該是17. 我環顧四周,但找不到答案。如何在Python中找到一個字符串中的確切單詞的索引

+0

Python新手,對我來說太複雜了! – Khan

+0

當我搜索「如何在字符串中找到一個單詞」時,我在該網站上發現了194個問題。你是否說這些答案沒有幫助? –

+0

8是正確答案,['find'](https://docs.python.org/2/library/string.html#string.find)返回第一個匹配子字符串的起始位置 – miraculixx

回答

0

代碼中的字符串不能用空格分隔。如果您想查找空間,則必須在要搜索的單詞中包含空格。您可能會發現它實際上會更有效爲您分割字符串成詞,然後迭代,如:

str = "This is a laughing laugh" 
strList = str.split(" ") 
for sWord in strList: 
    if sWord == "laugh": 
     DoStuff() 

正如你遍歷您可以將當前單詞的長度增加一個索引,當你發現這個詞,從循環中解脫出來。不要忘記佔空間!

+0

我可以發現字是在字符串中,我想知道它的索引。 – Khan

+0

我不好,你可以在迭代時添加每個單詞的長度。它可能比列出的正則表達式方法效率低,但我儘可能地避免使用Python中的正則表達式 - 我將它看作是一種腳本語言,並將其視爲一種易於閱讀的表達式。 – XtrmJosh

7

您應該使用正則表達式(與字邊界)find返回第一個的發生。然後使用match對象的start屬性來獲取起始索引。

import re 

string = 'This is laughing laugh' 

a = re.search(r'\b(laugh)\b', string) 
print(a.start()) 
>> 17 

你可以找到更多關於它如何工作的信息here

+0

太棒了!你能讓我知道如何在重新表達中使用變量,即我想用詞而不是(笑)? – Khan

+1

@Khan就像你會用任何Python字符串。你可以連接或使用'。格式',即'詞='笑'; re.search(r'\ b({})\ b'.format(word),string)' – DeepSpace

+0

這工作:re.compile(r'\ b%s \ b'%word,re.I)不確定爲什麼re.search(r'\ b({})\ b'.format(word),string)沒有... – Khan

0

這裏是沒有正則表達式的一種方法:

word = 'laugh'  
string = 'This is laughing laugh' 
words = string.split(' ') 
word_index = words.index(word) 
index = sum(len(x) + 1 for i, x in enumerate(words) 
      if i < word_index) 
=> 17 

這分裂串入的話,找到匹配詞的索引,然後總結了長度和空白字符的所有單詞前一個分隔它。

您當然應該使用正則表達式來提高性能和方便性。使用re模塊的等效如下:

r = re.compile(r'\b%s\b' % word, re.I) 
m = r.search(string) 
index = m.start() 

這裏\b裝置字邊界,請參閱re文檔。正則表達式可能非常令人畏懼。測試並找到正則表達式的一個好方法是使用regex101.com

+0

downvote所有你喜歡的,但請添加評論,所以我可以改善答案。 – miraculixx

+0

r = re.compile(r'\ b%s \ b'%word,re.I)像一個魅力一樣工作。您的完整解決方案也可行!非常感謝! – Khan

+0

downvote的原因是這個答案(它的兩個部分)已經以非常相似的形式存在。 – XtrmJosh

0

試試這個:

word = 'laugh'  
string = 'This is laughing laugh'.split(" ") 
index = string.index(word) 

這使得包含所有的單詞的列表,然後搜索相關詞語。然後,我想你可以添加列表中的所有元素小於指數的長度,並找到自己的索引方式

position = 0 
for i,word in enumerate(string): 
    position += (1 + len(word)) 
    if i>=index: 
     break 

print position 

希望這有助於。

相關問題