2013-04-22 116 views
2

我在python中創建了一個程序,它將通過句子列表並在句子中的大寫字母中查找單詞。目前我已經使用findall函數來獲取首都。查找字符串的索引號

這裏是我在一分鐘接收輸出的一個例子:

line 0: the dog_SUBJ bit_VERB the cat_OBJ 
['S'] ['U'] ['B'] ['J'] [] ['V'] ['E'] ['R'] ['B'] [] ['O'] ['B'] ['J'] 

不過,我想對於輸出爲完整的單詞,像這樣:

['SUBJ'] [] ['VERB'] [] ['OBJ'] 

我也想詞的索引如下:

['SUBJ'] [0] 
['VERB'] [1] 
['OBJ'] [2] 

可以這樣做嗎?我已經在終端上看到了上面所做的,我認爲使用'index'或類似的東西?

這裏是我下面的代碼(只要我有):

import re, sys 
f = open('findallEX.txt', 'r') 
lines = f.readlines() 
ii=0 
for l in lines: 
    sys.stdout.write('line %s: %s' %(ii, l)) 
    ii = ii + 1 
    results = [] 
    for s in l: 
     results.append(re.findall('[A-Z]+', s)) 

謝謝!任何幫助將不勝感激!

+0

要小心,因爲你的正則表達式匹配的句子等。健壯性我也將匹配下劃線的專有名詞/啓動大寫字母以及'm = re.findall('_ [AZ] +',string)'。如果不使用itertools:'list(enumerate(re.findall('[AZ] +',s)'),下劃線總是非常易於用字符串切片去除[m = [x [1:] for x in m]' – ejrb 2013-04-22 11:52:29

回答

2

喜歡的東西:

>>> s = 'the dog_SUBJ bit_VERB the cat_OBJ' 
>>> import re 
>>> from itertools import count 
>>> zip(re.findall('[A-Z]+', s), count()) 
[('SUBJ', 0), ('VERB', 1), ('OBJ', 2)] 

格式酌情......

+2

] ))' – root 2013-04-22 11:44:58

+0

@root yup - 如果OP要格式化元組,那麼它無論如何都不關心索引在哪個位置... – 2013-04-22 11:46:24

+0

對@ root的代碼稍作修改:'list(enumerate([x [ 1:] for x in re.findall('_ [AZ] +',l)]))'。現在適用於'dog_SUBJ bit_VERB Cat_OBJ'和類似的。 – ejrb 2013-04-22 11:59:36