python - 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")
解决方案
您的\d+
模式匹配任何 1 个或多个数字,因此该16
值匹配。您的[PB]+
字符类匹配一次P
或B
一次或多次,因此它限制数字以P
or开头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")
推荐阅读
- c++ - 包含 char 数组的结构体
- sql - 如何仅在 MS Access 2010 查询中显示所有员工缺勤日期?
- typescript - 没有重载的 Typescript 中的函数组合
- java - 使用 Java 打印非英语字符不正确
- ios - 为什么在 IndexPath 方法中使用 reloadItems 更新集合视图时看起来很慢?
- javascript - 我怎么知道我已经达到了 Node 中定义的线程限制?
- git - Github 中的自动合并 Pull Request [建议]
- java - 如何使用 java 8 修复以下 NullPointerException?
- ruby-on-rails - 数据表(无分页)> 表单提交中缺少参数
- angular - 使用 Microsoft 和 Twitter 登录