2015-04-02 51 views
0

如果我有這條線提取物什麼的線路是兩個詞之間

"he is a good man and he goes every day to a school" 

我想檢測一下兩個詞「他」,「和」,這樣的輸出將是

is a good man 

我想這

for line in file: 
    print line[line.index('he'): line.index('and')] 

此代碼使輸出

he is a good man 

我怎麼能這樣做?

回答

1

嘗試使用命令re.search()

import re 
s = "he is a good man and he goes every day to a school" 
result = re.search('he (.*) and', s) 
        #^-------^ Find string in between 'he' and 'and' 

print result.group(1) 

此輸出:

>>> 
is a good man 
>>> 

另外,如果你不喜歡的re模塊,還有很多其他的方法來做到這一點。

請看看這裏:Find string between two substrings

0

切片是指數包容和光潔度開始/ /索引獨家。這就是爲什麼它不包括「和」,但包括「他」

for line in file: 
    print line[line.index('he') - 1: line.index('and')]