Python 如何使用Xlsxwriter更改字符串中的特定字体颜色?
我想使用xlsxwriter更改字符串中的特定文本颜色。 我的想法是用彩色文本取代非彩色文本。 但它失败了 结果显示“TypeError:“Format”对象不能解释为整数” 看起来f“{error}”,cell_格式)是一个整数 这很奇怪,因为如果不能使用Python 如何使用Xlsxwriter更改字符串中的特定字体颜色?,python,python-3.x,xlsxwriter,Python,Python 3.x,Xlsxwriter,我想使用xlsxwriter更改字符串中的特定文本颜色。 我的想法是用彩色文本取代非彩色文本。 但它失败了 结果显示“TypeError:“Format”对象不能解释为整数” 看起来f“{error}”,cell_格式)是一个整数 这很奇怪,因为如果不能使用replace()来更改字符串中的单个字体颜色,我们还能做什么呢 我的输出是: 应该是: 我的代码: 导入xlsxwriter 从functools导入部分 定义x_in_y(单词,内部): 返回单词内部 工作簿=xlsxwriter.w
replace()
来更改字符串中的单个字体颜色,我们还能做什么呢
我的输出是:
应该是:
我的代码:
导入xlsxwriter
从functools导入部分
定义x_in_y(单词,内部):
返回单词内部
工作簿=xlsxwriter.workbook('C:\\Users\\Claude\\Desktop\\hello.xlsx')
工作表=工作簿。添加工作表()
单元格\格式=工作簿。添加\格式()
单元格格式。设置字体颜色(“红色”)
单词=[
(‘护照’、‘护照’),
('limmit','limit'),
(‘推杆’、‘推杆’)
]
句子=['putt dweqrerwr','dfsdf putt','limmit','pasport']
行=0
对于错误,请用文字纠正:
过滤的名称=过滤器(部分(x\u in\u y,内部=错误),句子)
下一个元素=下一个(过滤的名称,无)
如果下一个要素:
工作表.write(第0行,f“打字错误:{error}'应为{correct}')
工作表写入(行+1,0,下一个元素替换(错误,f“{错误}”,单元格格式))
对于已筛选名称中的名称:
工作表。写入(行+2,0,名称)
行+=2
工作簿.关闭()
因此,我在工作中遇到了一个类似的情况,我认为不可能部分格式化字符串,更不用说根据您的情况下的某些特定条件了。我看到了你的帖子和令人惊叹的John Mcnamara的回复,我决定尝试使用富字符串方法(我真的怀疑是否还有其他方法)
首先,让我提一下,我能够实现它使用熊猫和xlsxwriter。其次,使用pandas和xlsxwriter应该避免for循环(因为文件行越多,程序完成所需的时间就越长),但我无法以不同的方式实现它。您需要在那里应用一些错误处理,因为如果索引值不存在,它将引发一个值错误。最后,我没有包括一个单元格包含多个错误单词的情况,我们需要格式化所有错误单词
我会这样做:
import pandas as pd
# Create your dataframe
df = pd.DataFrame(data={'A': ["Typo: pasport 'should be passport'", 'pasport',
"Typo: limmit 'should be limit'", 'limmit',
"Typo: putt 'should be put'", 'putt dweqrerwr',
'dfsdf putt']})
# Create a list with the words that are wrong
wrong_words = ['pasport', 'limmit', 'putt']
# Kickstart the xlsxwriter
writer = pd.ExcelWriter('Testing rich strings.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', header=False, index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Define the red format and a default format
cell_format_red = workbook.add_format({'font_color': 'red'})
cell_format_default = workbook.add_format({'bold': False})
# Start iterating through the rows and through all of the words in the list
for row in range(0,df.shape[0]):
for word in wrong_words:
try:
# 1st case, wrong word is at the start and there is additional text
if (df.iloc[row,0].index(word) == 0) \
and (len(df.iloc[row,0]) != len(word)):
worksheet.write_rich_string(row, 0, cell_format_red, word,
cell_format_default,
df.iloc[row,0][len(word):])
# 2nd case, wrong word is at the middle of the string
elif (df.iloc[row,0].index(word) > 0) \
and (df.iloc[row,0].index(word) != len(df.iloc[row,0])-len(word)) \
and ('Typo:' not in df.iloc[row,0]):
starting_point = df.iloc[row,0].index(word)
worksheet.write_rich_string(row, 0, cell_format_default,
df.iloc[row,0][0:starting_point],
cell_format_red, word, cell_format_default,
df.iloc[row,0][starting_point+len(word):])
# 3rd case, wrong word is at the end of the string
elif (df.iloc[row,0].index(word) > 0) \
and (df.iloc[row,0].index(word) == len(df.iloc[row,0])-len(word)):
starting_point = df.iloc[row,0].index(word)
worksheet.write_rich_string(row, 0, cell_format_default,
df.iloc[row,0][0:starting_point],
cell_format_red, word)
# 4th case, wrong word is the only one in the string
elif (df.iloc[row,0].index(word) == 0) \
and (len(df.iloc[row,0]) == len(word)):
worksheet.write(row, 0, word, cell_format_red)
except ValueError:
continue
writer.save()
最终输出与所需输出相同:
我希望这会有所帮助。请参阅XlsxWriter文档中的
编写丰富的字符串()
。@jmcnamara是的,我已经尝试过了。但是write\u rich\u string()
需要首先对字符串进行切片。在我的示例中,next_elem是我的字符串,它包含错误的内容。如何分割下一个元素以使用write\u rich\u string()
?谢谢你的评论看到这个类似的问题和答案:@jmcnamara谢谢你。。。现在我不知道如何在工作表的顶部插入for循环。请在我的代码中写入\u rich\u字符串(row\u num,0,*tmp\u数组)
。因为在我的代码中只有一个工作表.write(行+1,0,下一个元素.replace(错误,f“{错误}”,单元格格式))
。很难理解如何将它们合并到我的代码中。。。