簡體   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