python - 如何使用python替换excel中单元格中的多个值?
问题描述
我有一个excel表:
ABC 01th,02th,03th,04th BCD 26th,02th CVF 01th
预期输出 ABC 01st,02nd,03rd,04th BCD 26th,02nd CVF 01st
我已经尝试过此代码,但如果单元格中仅存在该单个值,它将被替换。我需要用新值替换单元格中的所有错误值。有人能帮忙吗。
from xlrd import open_workbook
import xlsxwriter
rb = open_workbook("Dates.xlsx")
wb = xlsxwriter.Workbook('Updated_Workbook1.xlsx')
ws = wb.add_worksheet()
s_orig = rb.sheet_by_index(0)
NEW_Values= {'01th': '01st',
'02th': '02nd',
'03th': '03rd',
'21th': '21st',
'22th':'22nd',
'23th':'23rd',
'31th':'31st'}
for row in range(s_orig.nrows):
for col in range(s_orig.ncols):
if s_orig.cell(row,col).value in NEW_Values:
# s.write(row, col, NEW_Values[item])
ws.write(row, col, NEW_Values[s_orig.cell(row,col).value])
else:
ws.write(row, col, s_orig.cell(row,col).value)
wb.close()
解决方案
这里有一个建议:这个
import re
NEW_Values= {'01th': '01st', '02th': '02nd', '03th': '03rd', '21th': '21st',
'22th': '22nd', '23th': '23rd', '31th': '31st'}
re_new_values = re.compile(r'|'.join(NEW_Values))
def repl(match):
return NEW_Values[match.group()]
value = "ABC 01th,02th,03th,04th BCD 26th,02th CVF 01th"
print('Before:', value)
value = re_new_values.sub(repl, value)
print('After :', value)
将导致
Before: ABC 01th,02th,03th,04th BCD 26th,02th CVF 01th
After : ABC 01st,02nd,03rd,04th BCD 26th,02nd CVF 01st
这看起来像您的预期输出。r'|'.join(NEW_Values)
产生01th|02th|03th|21th|22th|23th|31th
在正则表达式搜索中起作用的模式,如'01th' or '02th' or ... or '31th'
. 该sub
方法是使用该函数通过映射repl
替换匹配项。value
NEW_Values
如果我没有犯任何错误,那么这可能是一种适合您的程序的方法:
import re
...
NEW_Values= {'01th': '01st', '02th': '02nd', '03th': '03rd', '21th': '21st',
'22th': '22nd', '23th': '23rd', '31th': '31st'}
re_new_values = re.compile(r'|'.join(NEW_Values))
def repl(match):
return NEW_Values[match.group()]
for row in range(s_orig.nrows):
for col in range(s_orig.ncols):
ws.write(row, col, re_new_values.sub(repl, s_orig.cell(row,col).value))
wb.close()
PS:您也可以使用lambda
一次性功能:
ws.write(row, col, re_new_values.sub(lambda m: NEW_Values[m.group()],
s_orig.cell(row,col).value))
推荐阅读
- python - 如何在python的两个列表中获得相同的布尔值
- python - 每当我运行此代码时,它都会向我显示 requests.exceptions.ConnectionError: HTTPSConnectionPool 错误
- python - 使用 QtQuick.Controls 中的任何内容都会引发受保护的模块错误
- angular - IdentityServer4 - Angular 如何将默认登录页面更改为 Angular 组件
- python-3.x - 安装 Kivy 模块时出错
- javascript - 在不同的函数中重复变量声明
- java - Windows 10 上的 JDK 提取和安装错误问题
- python - 从 Skopt 中的检查点恢复 gp_minimize 进程
- postgresql - pgp_sym_encrypt postgres 性能问题
- c# - SessionState cookieName 重命名 Asp.net_Session_ID 使会话无效 ["CaptchaVerify"]