gpt4 book ai didi

Python,从Excel列中提取数字并作为输出写入

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

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

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

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

enter image description here

我该如何改进它?谢谢。

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+模式匹配任何一位或多位数字,因此 16值匹配。你的[PB]+字符类匹配 PB一次或多次,因此它限制数字前面有 PB .因为您想要匹配任何数字,所以您实际上不需要该限制(如果 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")

关于Python,从Excel列中提取数字并作为输出写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52034775/

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