gpt4 book ai didi

python - 使用 Python 在 Excel (.xlsx) 中查找和替换字符串

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:45 25 4
gpt4 key购买 nike

我正在尝试替换 .xlsx 工作表中的一堆字符串(约 70k 行,38 列)。我有一个要在文件中搜索和替换的字符串列表,格式如下:-

bird produk - bird product
pig - pork
ayam - chicken
...
kuda - horse

要搜索的词在左侧,替换词在右侧(查找“bird produk”,替换为“bird Product”。我的 .xlsx 工作表如下所示:-

name     type of animal     ID
ali pig 3483
abu kuda 3940
ahmad bird produk 0399
...
ahchong pig 2311

我正在寻找最快的解决方案,因为我要搜索的列表中有大约 200 个单词,并且 .xlsx 文件非常大。我需要使用 Python 来实现此目的,但我愿意接受任何其他更快的解决方案。

编辑:-添加工作表示例

Edit2:-尝试了一些Python代码来读取单元格,花了相当长的时间来读取。有什么指点吗?

from xlrd import open_workbook
wb = open_workbook('test.xlsx')

for s in wb.sheets():
print ('Sheet:',s.name)
for row in range(s.nrows):
values = []
for col in range(s.ncols):
print(s.cell(row,col).value)

谢谢!

Edit3:-我终于想通了。 VBA 模块和 Python 代码都可以工作。我改用 .csv 来使事情变得更容易。谢谢你!这是我的 Python 代码版本:-

import csv

###### our dictionary with our key:values. ######
reps = {
'JUALAN (PRODUK SHJ)' : 'SALE( PRODUCT)',
'PAMERAN' : 'EXHIBITION',
'PEMBIAKAN' : 'BREEDING',
'UNGGAS' : 'POULTRY'}


def replace_all(text, dic):
for i, j in reps.items():
text = text.replace(i, j)
return text

with open('test.csv','r') as f:
text=f.read()
text=replace_all(text,reps)

with open('file2.csv','w') as w:
w.write(text)

最佳答案

我会将文本文件的内容复制到 Excel 文件中的新工作表中,并将该工作表命名为“查找”。然后使用文本到列来获取此新工作表的前两列中的数据,从第一行开始。

将以下代码粘贴到 Excel 中的模块中并运行它:

Sub Replacer()
Dim w1 As Worksheet
Dim w2 As Worksheet

'The sheet with the words from the text file:
Set w1 = ThisWorkbook.Sheets("Lookup")
'The sheet with all of the data:
Set w2 = ThisWorkbook.Sheets("Data")

For i = 1 To w1.Range("A1").CurrentRegion.Rows.Count
w2.Cells.Replace What:=w1.Cells(i, 1), Replacement:=w1.Cells(i, 2), LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next i

End Sub

关于python - 使用 Python 在 Excel (.xlsx) 中查找和替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26221907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com