问题描述
我已经使用python的xlsxwriter和openpyxl模块来获取丰富的字符串,但是它们没有提供太多的灵活性来搜索动态字符串的特定单词并突出显示该单词.有谁对此有更好的选择?或者,我尝试将动态字符串分成两个部分,并尝试在两者之间添加样式以与xlsxwriter.write_rich_string()格式合并.下面是示例代码:....一些起始代码
I have used xlsxwriter and openpyxl module of python for rich string but they don't provide that much flexibility for searching specific word of dynamic string and highlight that one.Does anyone have better option for this? alternatively, I am trying to split the dynamic string into and trying to add styles in between to incorporate with the xlsxwriter.write_rich_string() format.below is the sample code: ....some starting code here
completestring="Stackoverflow is best site" #this will be a dynamic string ,and need to highlight **best** here
str1="Stackoverflow is"
str2="best"
str3="site"
bold= workbook.add_format()
bold.set_bold()
bold.set_font_color('red')
stringpart=[str1,bold,str2,str3]
worksheet.write_rich_string('A1',*stringpart)
推荐答案
这是可以在Python中处理的东西.您只需要找出一种方法即可根据单词拆分split并在列表中保留单词.
This is something that can be handled in Python. You just need to figure out a way to split stings based on a word and maintain the word in the list.
这是一种实现方法:
import re
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True, 'color': 'red'})
# Make the column wider for clarity.
worksheet.set_column('A:A', 30)
# Some sample test data.
strings = ["The best website",
"The bestest website",
"The best of the best",
"best of the best",
" best of the best ",
"The BEST website"]
# Iterate over the strings.
for row_num, string in enumerate(strings):
# Split the sentence on the word "best", on word boundaries.
segments = re.split(r'(\bbest\b)', string)
if len(segments) == 1:
# String doesn't have a match, write as a normal string.
worksheet.write(row_num, 0, string)
else:
# Iternate through the segments and add a format before the matches.
tmp_array = []
for segment in segments:
if segment == 'best':
# Add a bold format before the matched word.
tmp_array.append(bold)
tmp_array.append(segment)
elif not segment:
# Ignore blank segments.
pass
else:
tmp_array.append(segment)
worksheet.write_rich_string(row_num, 0, *tmp_array)
workbook.close()
输出:
这篇关于Excel for python中动态值字符串的富文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!