我正在嘗試按照以下語法替換 Excel 作業表中的一組占位符文本:
{{text_to_replace}}
例如單元格 A1 可以保存這個值;
"We are looking for {{item_placeholder}}"
然后我有一個替換字典:例如
{'item_placeholder': "apples, 'location_placeholder': "UK"}
所以我希望替換的文本看起來像這樣:
"We are looking for apples"
例如,也有可能需要在同一個單元格中替換兩個占位符;
"We are looking for {{item_placeholder}} in the {{location_placeholder}}
這是迭代前作業表的外觀:

這是預期的輸出:

所以我撰寫了代碼來迭代每個單元格(我知道這里有很多關于迭代行的最佳方法的討論,但最后我選擇了迭代),但是資料框沒有被更新與新值。
workbook = writer.book
worksheet = writer.sheets[sheet_name]
for row in df.itertuples():
for col_num, value in enumerate(df.columns.values):
cell_value = df.iloc[row.Index][col_num]
for var_name, replacement in variables.items():
if str(replacement):
if type(cell_value) == str and "{{" var_name "}}" in cell_value:
cell_value = str(cell_value).replace("{{" var_name "}}", str(replacement))
else:
raise ValueError(f'"replacement" in dict is mandatory. Missing for {var_name}')
if type(cell_value) == str:
worksheet.write(row.Index, col_num, cell_value)
workbook.close()
我確定我遺漏了一些基本的東西,但我是 Panda's 和 Python 的新手,并在這里查閱了 xlsxwriter 的檔案,這讓我認為它應該可以作業
uj5u.com熱心網友回復:
考慮只讀取電子表格,然后將其重寫為檔案。我知道這不是您特別要問的,但我使用您所做的相同回圈并且這有效。可能是在您的代碼中,您只需要使用str(var_name)而不僅僅是var_name. 只是猜測,因為您沒有說是否有錯誤或只是沒有更新。
Anywho,這里有兩個示例,您可以在其中讀取檔案,對單個列進行操作,另一個示例可以對整個資料幀進行操作。
使用此資料創建簡單的 .xlsx 檔案,作業表名稱為“a”
this {{item_placeholder}} in the {{location_placeholder}} a test to find {{item_placeholder}}
this is a test to find {{item_placeholder}}
this is {{item_placeholder}} test to find {{item_placeholder}} in the {{location_placeholder}}
選項1
replacement = {'item_placeholder': "apples", 'location_placeholder': "UK"}
df = pd.read_excel('test.xlsx', header=None, sheet_name =['a'])['a']
for k, v in replacement.items():
# print(k,v)
df.iloc[:, 6] = df.iloc[:, 6].str.replace('{{' str(k) '}}', v)
print(df)
0 1 2 3 4 5 6
0 this {{item_placeholder}} in the {{location_placeho... a test to find apples
1 this is a test to find apples
2 this is {{item_placeholder}} test to find apples in the UK
選項 2
replacement = {'item_placeholder': "apples", 'location_placeholder': "UK"}
df = pd.read_excel('test.xlsx', header=None, sheet_name =['a'])['a']
for k, v in replacement.items():
# print(k,v)
df = df.replace('{{' str(k) '}}', v, regex=True)
print(df)
0 1 2 3 4 5 6
0 this apples in the UK a test to find apples
1 this is a test to find apples
2 this is apples test to find apples in the UK
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364710.html
標籤:Python 蟒蛇-3.x 熊猫 xlsxwriter
下一篇:使用輸入將數字轉換為羅馬字符
