为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Python 搜索和替换 excel (.xls) 文件中的字符串?

如何使用 Python 搜索和替换 excel (.xls) 文件中的字符串?

LEATH 2023-05-09 10:56:34
我正在尝试在 excel 文件 (xls) 中使用搜索和替换字符串,实际上 - 我需要查找字符串并在前缀 * 之前添加。例如但我收到一个错误:LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced}NameError: name 'two_replaced' is not defined代码:from xlrd import open_workbookfrom xlutils.copy import copyimport xlsxwriterrb = open_workbook("template.xlsx")# Create an new Excel file and add a worksheet.wb = xlsxwriter.Workbook('Updated_Workbook1.xlsx')ws = wb.add_worksheet()s_orig = rb.sheet_by_index(0)LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced,}for row in range(s_orig.nrows):    for col in range(s_orig.ncols):        if s_orig.cell(row,col).value in LVdemact:            # s.write(row, col, LVdemact[item])            ws.write(row, col, LVdemact[s_orig.cell(row,col).value])        else:            ws.write(row, col, s_orig.cell(row,col).value)wb.close()
查看完整描述

2 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

问题在于 -LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced,}

变量two_replacedsix_replaced并且five_replaced未定义。你想让它成为一个字符串吗?然后以这种方式定义它 -

LVdemact = {'two': 'two_replaced', 'six': 'six_replaced', 'five': 'five_replaced'}


查看完整回答
反对 回复 2023-05-09
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

你可以用这个


df = pd.DataFrame() # Your dataframe


for column in df.select_dtypes('object'):

    df[column] = df[column].str.replace('toreplace','newword')


查看完整回答
反对 回复 2023-05-09
  • 2 回答
  • 0 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信