search

Home  >  Q&A  >  body text

xlwt - How to add color to specified words in python and write it to Excel document?

.......

Create text color function set_color

def set_color(color,bold=False):

style = xlwt.XFStyle() 
font = xlwt.Font() 
font.colour_index = color
style.font = font
return style

Find the specified word and add color

for i in range(nrow1): #Read the number of rows and loop

pn=[]
pl=[]
a=table1.row_values(i)[0] 
she1.write(i,0,a)      #写入Excel

datafen= jiebtext(a)   #利用jieba函数,进行分词

for nword in datafen:
    if nword in nwords():  #判断已分好的分词是否符合指定某个词语
        pn.append(nword)
        
for l in range(len(pn)):    #读取符合指定词语的长度,并循环
    c= datafen.index(pn[l])  #找出符合指定词语的索引号
    datafen[c]=pn[l],set_style(5,True)    #将已经设置好颜色的词语并重新赋值
    data=a.replace(pn[l],**str(datafen[c]**))    #转化字符串,并把无颜色的词语替换为有颜色的词语
    print data  #输入结果

.....

    she1.write(i,l+1,data)

Result:
He is a good person, we all like him, and he loves to help others, but life(u'u5c0fu6c14', <xlwt.Style.XFStyle object at 0x000000000334BCF8>), fight every day.
He is a good person, and we all like him. In addition, he loves to help others, but he lives a stingy life every day(u'u6253u67b6', <xlwt.Style.

I have now found a problem in the code (in data=a.replace(str(pn[l]), str(datafen[c]))). If the str type is not added, a type error will be prompted. The problem is that after writing to Excel, the bold characters in the above results will appear in the table. How can I add color to the words and write them into the Excel document?

过去多啦不再A梦过去多啦不再A梦2749 days ago755

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-18 10:46:56

    Why do you feel

    a.replace(str(pn[l]),str(datafen[c]))

    Here pn[l] needs to add str. Isn’t it itself a str type?

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-18 10:46:56

    Insert a statement in the middle to print what the type of data is. This may be the problem. It is recommended to use xlsxwriter

    reply
    0
  • Cancelreply