2017-02-19 33 views
3

我想製作一段簡單的代碼,其中包含一段文本,掃描關鍵字並打印關鍵字以及接下來的5個字符。請注意,關鍵字可能會在文本中出現多次。打印關鍵字後面出現的5個字符

string = 'my name is luka 90/91, I live on the second floor' 
    keyword = 'luka' 

    if key in string: 
     print (key + key[0:5]) 

輸出應該是盧卡90 \ 91

+1

與下一個五個字符沿關鍵字實際上將是''盧卡90/9''。 – jonrsharpe

+0

當'keyword'出現時,您想要打印所有接下來的5個字符嗎?或只有第一次出現? –

回答

5

使用str.find,你可以得到匹配的字符串的索引:

>>> string = 'my name is luka 90/91, I live on the second floor' 
>>> keyword = 'luka' 
>>> string.find(keyword) 
11 

>>> i = string.find(keyword) 
>>> string[i:i+len(keyword)+5] 
'luka 90/9' 
>>> string[i:i+len(keyword)+5+1] # +1 (count space in between) 
'luka 90/91' 

UPDATE要獲取所有的事件,您需要在循環中找到子字符串。

string = 'my name is luka 90/91, I live on the second floor luka 12345' 
keyword = 'luka' 

i = 0 
while True: 
    i = string.find(keyword, i) # `i` define from where the find start. 
    if i < 0: 
     break 
    j = i + len(keyword) + 5 + 1 
    print(string[i:j]) 
    i = j 

UPDATE溶液使用re.findall

>>> string = 'my name is luka 90/91, I live on the second floor luka 12345' 
>>> keyword = 'luka' 
>>> import re 
>>> re.findall(re.escape(keyword) + '.{5}', string) 
['luka 90/9', 'luka 1234'] 
>>> re.findall(re.escape(keyword) + '.{6}', string) 
['luka 90/91', 'luka 12345'] 
  • luka匹配字面。 .{5}符合下列任何5個字符。
  • 如果您想匹配字符,即使它們少於5個字符。改爲使用.{1,5}
  • re.escape對於luka不是必要的。如果有特殊字符在正則表達式中有特殊含義,則這是必需的。
+1

輸出應該包含關鍵字明顯... –

+0

@JonClements,感謝您的評論。我相應地更新了答案。 – falsetru

+1

OP也提到子字符串可以出現多次。你可能想提到'str.index'的第二個參數。 – dabadaba

1
import re 

string = 'my name is luka 90/91, I luka onthe second floor' 
keyword = 'luka' 

i = [m.start() for m in re.finditer(keyword, string)] 
K = [[keyword + ' '+ string[len(keyword)+1+j:len(keyword)+j+5+1]] for j in i] 

還是一個更好的解決方案: L = re.findall(keyword + ' .{5}', string)

print(K)

OUTPUT:

[['luka 90/91'], ['luka onthe']] 

print(L)

OUTPUT:

['luka 90/91', 'luka onthe']

我增加了一個額外的1的空間,並且假設關鍵字後keyword足夠大。否則空間會發生。如果這是不需要的,它可以被修復。但是這樣的行爲並不是由你自己定義的。

+2

任何你不會使用的理由:'re.findall('luka。{5}',string)'? –

+0

@JonClements nope。我只是給了他一個我知道的解決方案。我會試試這個,如果需要的話重新編輯。謝謝你的提示。 –

+0

可能要'{,5}',如果高達但必須有5個或更多字母跟在關鍵字 –

0
string = 'my name is luka 90/91, I live on the second floor. luka means nothing' 
keyword = 'luka' 
split_array = string.split(keyword) 
for x in split_array[1:]: # If keyword is found split array would contain more than one element 
    print keyword, x.strip()[:5] 

OUTPUT

luka 90/91 
luka means 
相關問題