[英]Trying to incorporate RegEX with Excel exercise from "Automate the Boring Stuff with Python"
我正在嘗試使用 Python 第 13 章第 315 頁修改“自動化無聊的東西”中的項目代碼,以將正則表達式合並到代碼中。 對於我的 Excel 工作表,我有一個傳感器名稱列表,需要正確填寫“單位”列(示例見下圖)。 我已經更新了項目代碼字典以將相應的單位合並到 _BattV、_ft_H20 等中。 由於傳感器名稱的結構為 XXX_123_BattV,其中 XXX 是項目代碼,123 是傳感器編號,_BattV 是表示傳感器類型的后綴。 我想使用 RegEX 匹配每個傳感器名稱的最后一個塊,以便代碼將使用 _BattV 更新每個傳感器,單位列中的“伏特”等等。
這是到目前為止我從項目示例中修改的代碼。
#! python3
#updateProduce.py - Corrects cost in produce sales spreadsheet.
import openpyxl
filename = 'stackoverflowexample.xlsx'
wb = openpyxl.load_workbook(filename)
sheet = wb['stackoverflowexample']
#The produce types and their updated prices
UNIT_UPDATES = {
'_BattV': 'volts',
'_ft_H2O': 'Feet of H20',
'_GWE': 'Elevation (ft)',
'_PSI': 'PSI',
'_TempC': 'deg C'}
#Loop through the rows and update the prices.
for rowNum in range(2, sheet.max_row): #skip the first row
Sensor_name = sheet.cell(row=rowNum, column=1).value
if Sensor_name in UNIT_UPDATES:
sheet.cell(row=rowNum, column=2).value = UNIT_UPDATES[Sensor_name]
wb.save(f'updatedstackoverflowexample.xlsx')
這是我從本書的 RegEx 部分收集到的內容:
import re
unitRegex = re.compile(r'_BattV|_ft_H2O|_GWE|_PSI|_TempC')
voltRegex = re.compile(r'.*_BattV')
fth20Regex = re.compile(r'.*_ft_H2O')
gweRegex = re.compile(r'.*_GWE')
psiRegex = re.compile(r'.*_PSI')
tempRegex = re.compile(r'.*_TempC')
mo = unitRegex.search('insert cell data here')
我也很好奇是否最好先運行 Regex 並將所有匹配項輸入到字典中,然后再運行其余部分。 或者最好將它合並到 for 循環中。
最后是示例截圖:
顯示數據結構的 Excel 電子表格的屏幕截圖:
雖然您可以使用正則表達式執行此操作,但您可以簡單地拆分字符串:
units = {"BattV":"volts", …}
for cell in ws[A][1:]:
project, sensor, unit = cell.value.split("_")
cell.offset(column=2).value = units[unit]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.