[英]How to extract specific numbers between combination of strings and characters from excel columns using python?
我是 python excel 自动化的新手。 请帮助我提取列中不同字符中存在的特定数字。
Actual DATA
Column A
kDGK~202287653976 ~LD ~ 8904567
SIP~12335678 ~202267858245~LD~8936272
SIN112592~ LD ~ SIN112592
0194X0322 ~ LD ~ 202243296291
预计 Output
Column B
202287653976
202267858245
-
202243296291
我想提取从“2022”开始并且没有的 12 位数字应该留下一个空白单元格。 条件很简单,但我不知道该怎么做。
提前致谢。
要在 Python 中提取您的号码,只需使用正则表达式:
import re
col_a = 'kDGK~202287653976 ~LD ~ 8904567'
match = re.search(r'(2022\d+)', col_a)
if match:
col_b = match[0]
如果未找到任何内容,则match
将为None
或“匹配对象” - 在这种情况下,`match[0]' 将是您想要的数字
编辑
上面的正则表达式将匹配“2022”后跟任意数量的数字。 如果您想要在“2022”之后正好是 8 位数字,则应该改写re.search(r'(2022\d{8})', col_a)
。
编辑 2
假设您使用的是openpyxl
,完整代码将类似于
from openpyxl import load_workbook
import re
wb = load_workbook('somefile.xlsx')
ws=wb.active
for row in range(len(ws['A'])): #number of used cells in column A
match = re.search(r'(2022\d+)', ws.cell(row,1).value
if match:
ws.cell(row,2).value = match[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.