Skip to main content
 首页 » 编程设计

python之根据词性在终端中为文本着色

2025年05月04日8zfyouxi

我想为终端中的句子着色,使名词为蓝色,动词为绿色。其他一切都是黑色的。

到目前为止,我尝试使用 nltk 和 colorama 模块来达到这个目的。

import nltk 
from colorama import Fore 

此代码将找出名词和动词,因此动词是 VB 或 VBD,名词是 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 不变(仅应用所需的颜色)?

请您参考如下方法:

这个怎么样?它使空格与原始文本完全相同。不过,我确实认为动词应该是红色的。

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