0

私は文のファイルを調べて、それらの文の中から行ごとに大文字を抜き出そうとしています。

私が取り組んでいるデータファイルは次のとおりです。

the dog_SUBJ bit_VERB the cat_OBJ
the man_SUBJ ran_VERB
the cat_SUBJ ate_VERB the cheese_OBJ

基本的には、行ごとに 'SUBJ'、'VERB'、'OBJ' を出力するプログラムが必要です。ただし、現在取り組んでいるスクリプトの各行では、出力は、その行の大文字だけではなく、各行のファイル内のすべての大文字です。

これが私が今得ている出力です:

行 0:the dog_SUBJ bit_VERB the cat_OBJ

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

ライン1:the man_SUBJ ran_VERB

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

2行目:the cat_SUBJ ate_VERB the cheese_OBJ

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

たとえば、0 行目、'SUBJ'、'VERB'、'OBJ' を、その行にあるものとしてプログラムに出力させたいとします。

現時点で使用しているスクリプトは次のとおりです。

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 i in lines:
        results += re.findall(r'[A-Z]+', i)

ありがとう!

4

2 に答える 2

0

正規表現なし:

from itertools import chain, groupby
with open('text.txt') as f:
    print [''.join(g) for k, g in 
           groupby(chain.from_iterable(f), key=str.isupper) if k]

['SUBJ', 'VERB', 'OBJ', 'SUBJ', 'VERB', 'SUBJ', 'VERB', 'OBJ']
于 2013-04-19T13:18:23.857 に答える