繁体   English   中英

查找列表中与特定格式匹配的所有项目

[英]Find all items in a list that match a specific format

我正在尝试查找格式为“ ######-##”的列表中的所有内容

我以为我的以下代码中有正确的主意,但它没有打印任何内容。 我列表中的某些值具有该格式,我认为应该将其打印出来。 你能告诉我怎么了吗?

for line in list_nums:
    if (line[-1:].isdigit()):
        if (line[-2:-1].isdigit()):
            if (line[-6:-5].isdigit()):
                if ("-" in line[-3:-2]):
                    print(list_nums)

我列表中的值包含123456-56和123456-98-98之类的格式,这就是我在上面所做的原因。 它是从Excel工作表中提取的。

这是我更新的代码。

import xlrd
from re import compile, match

file_location = "R:/emily/emilylistnum.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
regexp = compile(r'^\d{d}-\d{2}$')
list_nums = ""


for row in range(sheet.nrows):
    cell = sheet.cell_value(row,0)
    if regexp.match(cell):
        list_nums += cell + "\n"
        print(list_nums)

我的Excel工作表包括: 581094-001 581095-001 581096-001 581097-01 5586987-007 SMX53-5567-53BP 552392-01-01 552392-02 552392-03-01 552392-10-01 552392-10-01 580062 580063 580065 580065 580066 543921-01 556664-55

(在一列中向下的每个单元格中)

如果只需要匹配模式######-## (其中#是数字):

>>> from re import compile, match
>>> regexp = compile(r'^\d{6}-\d{2}$')
>>> print([line for line in list_nums if regexp.match(line)])
['132456-78']

说明

您可以将模式compile成regexp对象,以在匹配时更有效。 正则表达式为^\\d{6}-\\d{2}$ ,其中:

^  # start of the line
\d{6}-\d{2}  # 6 digits, one dot then 2 digits
$  # end of the line

在正则表达式中, \\d表示数字(0到9之间的整数),而{6}表示6次。 因此\\d{3}表示3位数字。 您应该阅读有关regexp的Python文档。


完整代码

根据您的评论的示例:

file_location = 'file.xlsx'
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
regexp = compile(r'^\d{6}-\d{2}$')

list_nums = ''
for row in range(sheet.nrows):
    cell = sheet.cell_value(row, 0)
    if regexp.match(cell):
        list_nums += cell + "\n"

您的代码似乎做正确的事,不同的是您希望它打印 line的值而不是list_nums的值。

解决当前任务的另一种方法是使用正则表达式,它是模式识别的理想选择。

编辑:现在将list_nums编码为单个字符串

import re

rx = re.compile('\d{6}-\d{2}\Z')
for line in list_nums.split('\n'):
  if rx.match(line):
    print line

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM