尝试从Excel文件的列中提取数字,然后将其写入下一列。
匹配条件:长度为5的任意数量,是否以“ PB”开头
我将数字匹配的长度限制为五个,但是提取了“ 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")
您的\d+
模式匹配任何1个或多个数字,因此16
值是匹配的。您的[PB]+
字符类匹配一次P
或B
一次或多次,因此它限制了以P
或开头的数字B
。您想匹配任何数字时,实际上并不需要该限制(如果A
可以在前面加上可选的内容,则该限制不再有意义)。
您似乎也需要准确地提取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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句