首页 > 解决方案 > Python,从 Excel 列中提取数字并写入输出

问题描述

尝试从 Excel 文件中的列中提取数字,并将它们写入下一列。

匹配标准:任意数量的长度为 5,以“PB”开头或不以“PB”开头

我将数字匹配的长度限制为 5,但是提取了“16”(第 2 行,D 列)

在此处输入图像描述

我怎样才能改进它?谢谢你。

import xlwt, xlrd, re
from xlutils.copy import copy 

workbook = xlrd.open_workbook("C:\\Documents\\num.xlsx")
old_sheet = workbook.sheet_by_name("Sheet1")

wb = copy(workbook) 
sheet = wb.get_sheet(0)

number_of_ships = old_sheet.nrows

for row_index in range(0, old_sheet.nrows):

    Column_a = old_sheet.cell(row_index, 0).value   
    Column_b = old_sheet.cell(row_index, 1).value

    a_b = Column_a + Column_b

    found_PB = re.findall(r"[PB]+(\d{5})", a_b, re.I)
    list_of_numbers = re.findall(r'\d+', a_b)

    for f in found_PB:
        if len(f) == 5:
            sheet.write(row_index, 2, "";"".join(found_PB))

    for l in list_of_numbers:
        if len(l) == 5:
            sheet.write(row_index, 3, "";"".join(list_of_numbers))

wb.save("C:\\Documents\\num-1.xls")    

标签: pythonregexexcel

解决方案


您的\d+模式匹配任何 1 个或多个数字,因此该16值匹配。您的[PB]+字符类匹配一次PB一次或多次,因此它限制数字以Por开头B。当您想匹配任何数字时,您实际上不需要该限制(如果 anA前面可以有一些optional,则该限制不再有意义)。

当在它们之前或之后没有其他数字时,您似乎还需要准确提取 5 位字符串。你可以用(?<!\d)\d{5}(?!\d). 负前瞻确保当前(?<!\d)位置左侧没有数字,\d{5}消耗 5 位,(?!\d)负前瞻确保当前位置右侧没有数字。这使该if len(l) == 5:行变得多余,您可以省略与list_of_numbers.

所以,你可以只使用

import xlwt, xlrd, re
from xlutils.copy import copy 

workbook = xlrd.open_workbook("C:\\Documents\\num.xlsx")
old_sheet = workbook.sheet_by_name("Sheet1")

wb = copy(workbook) 
sheet = wb.get_sheet(0)

number_of_ships = old_sheet.nrows

for row_index in range(0, old_sheet.nrows):

    Column_a = old_sheet.cell(row_index, 0).value   
    Column_b = old_sheet.cell(row_index, 1).value

    a_b = Column_a + Column_b

    found_PB = re.findall(r"(?<!\d)\d{5}(?!\d)", a_b)

    for f in found_PB:
            sheet.write(row_index, 2, "";"".join(found_PB))

wb.save("C:\\Documents\\num-1.xls")    

推荐阅读