2

名詞が青色、動詞が緑色になるように端末の文に色を付けたいと思います。それ以外は黒になります。

これまでのところ、この目的のためnltkにモジュールを使用しようとしました。colorama

import nltk
from colorama import Fore

このコードは名詞と動詞を見つけるので、動詞はVBorVBDで、名詞はNNです。

s = nltk.word_tokenize(sample_sentence)
tagged_text = nltk.pos_tag(s)
print tagged_text

[('Stately', 'RB'), (',', ','), ('plump', 'VB'), ('Buck', 'NNP'), ('Mulligan', 'NNP'), ('came', 'VBD'), ('from', 'IN'), ('the', 'DT'), ('stairhead', 'NN'), (',', ','), ('bearing', 'VBG'), ('a', 'DT'), ('bowl', 'NN'), ('of', 'IN'), ('lather', 'NN'), ('on', 'IN'), ('which', 'WDT'), ('a', 'DT'), ('mirror', 'NN'), ('and', 'CC'), ('a', 'DT'), ('razor', 'NN'), ('lay', 'NN'), ('crossed', 'VBD'), ('.', '.')]

色付きのテキストを印刷したいときは、次を使用します。

print Fore.BLUE + some_noun
print Fore.GREEN + some_verb
print Fore.BLACK + something_else

文を印刷するのに問題があります。tagged_text変更されていないものを印刷するようにどのようにループしますかsample_sentence(目的の色のみが適用されます)。

4

1 に答える 1

1

これはどう?元のテキストとまったく同じように空白を保持します。しかし、動詞は赤であるべきだと私は信じています。

from colorama import Fore, init
import re
init()

tagged_text = [('Stately', 'RB'), (',', ','), ('plump', 'VB'), ('Buck', 'NNP'), ('Mulligan', 'NNP'), ('came', 'VBD'),
                ('from', 'IN'), ('the', 'DT'), ('stairhead', 'NN'), (',', ','), ('bearing', 'VBG'), ('a', 'DT'), 
                ('bowl', 'NN'), ('of', 'IN'), ('lather', 'NN'), ('on', 'IN'), ('which', 'WDT'), ('a', 'DT'),
                ('mirror', 'NN'), ('and', 'CC'), ('a', 'DT'),('razor', 'NN'), ('lay', 'NN'), ('crossed', 'VBD'),
                ('.', '.'), ('The', 'DET'), ('function', 'NN'), ('f', 'SYM'), ('(','('),('x','SYM'),(',',','),
                ('y','SYM'),(')',')'),('takes','VB'), ('two', 'CD'), ('arguments', 'NN'), ('.','.')]
origtext = 'Stately, plump Buck Mulligan came from the stairhead, bearing a bowl of lather on which a mirror and a razor lay crossed. The function f(x,y) takes two arguments.'

colordict = {'VB': Fore.GREEN, 'VBD': Fore.GREEN, 'NN': Fore.BLUE}

colorwords = ''
for word, tag in tagged_text:
    color = Fore.BLACK
    word = re.match(r'\s*%s\s*' % re.escape(word), origtext).group()
    origtext = origtext.split(word,1)[1]
    if tag in colordict:
        color = colordict[tag]
    colorwords += color + word

print colorwords
于 2012-10-29T17:39:20.830 に答える