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 回答