我使用一个空列表对字符串进行切片和格式化
但我不想在结果中看到一些字符串
示例:我不想显示“riichard”和“Canturyoo”
我如何设置类似于黑名单的内容直接添加到列表中,以便轻松排除我不想要的单词
Like:(使用减号(-)排除单词)
words = [
('riich', 'rich',-'riichard',-'riicharson'),
('cantury', 'century',-'canturyooo'),
Regex是排除它们的唯一方法吗
还是有更好的方法
这是我的代码:
import xlsxwriter
from functools import partial
def x_in_y(word, inner):
return inner in word
workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
words = [
('riich', 'rich'),
('cantury', 'century'),
]
sentence = [
'riichard dweqrerwr',
'he is very riich',
'this is 21st cantury',
'canturyooo mankind',
]
row = 0
red = workbook.add_format({'font_color': 'red'})
black = workbook.add_format({'font_color': 'black'})
for wrong, correct in words:
filtered_names = filter(partial(x_in_y, inner=wrong), sentence)
next_elem = next(filtered_names, None)
if next_elem:
worksheet.write(row, 0, f"Typo: {wrong} 'should be {correct}'")
row += 1
while next_elem:
if len(next_elem) == len(wrong):
worksheet.write(row, 0, next_elem, red)
else:
slices = []
startIndex = 0
index = next_elem.find(wrong)
while index != -1:
if next_elem[startIndex: index]:
slices.append(black)
slices.append(next_elem[startIndex: index])
slices.append(red)
slices.append(next_elem[index: index + len(wrong)])
startIndex = index + len(wrong)
index = next_elem.find(wrong, startIndex)
if next_elem[startIndex:]:
slices.append(black)
slices.append(next_elem[startIndex:])
worksheet.write_rich_string(row, 0, *slices)
row += 1
next_elem = next(filtered_names, None)
workbook.close()
结果:
我希望它看起来像:
目前没有回答
相关问题 更多 >
编程相关推荐