【问题标题】:How to search and replace string in excel (.xls) file using Python?如何使用 Python 搜索和替换 excel (.xls) 文件中的字符串?
【发布时间】:2020-08-08 06:01:19
【问题描述】:

我正在尝试在 excel 文件 (xls) 中使用搜索和替换字符串,实际上 - 我需要查找字符串并在前缀 * 之前添加。 例如

但我得到一个错误:

LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced}
NameError: name 'two_replaced' is not defined

代码:

from xlrd import open_workbook
from xlutils.copy import copy
import xlsxwriter

rb = 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()

【问题讨论】:

  • 在定义LVdemact之前,您至少需要添加two_replaced = "two_replaced"之类的内容。

标签: python excel xlrd xlutils


【解决方案1】:

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

变量two_replacedsix_replacedfive_replaced 未定义。你希望这是一个字符串吗?然后以这种方式定义它-

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

【讨论】:

    【解决方案2】:

    你可以用这个

    df = pd.DataFrame() # Your dataframe
    
    for column in df.select_dtypes('object'):
        df[column] = df[column].str.replace('toreplace','newword')
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 2012-04-01
      • 2011-12-13
      • 1970-01-01
      • 2010-11-14
      • 2014-12-06
      相关资源
      最近更新 更多