gpt4 book ai didi

python - 使用 re.match 过滤字符串列表时失败

转载 作者:IT老高 更新时间:2023-10-28 20:37:58 25 4
gpt4 key购买 nike

我想使用正则表达式过滤 python 中的字符串列表。在以下情况下,仅保留扩展名为“.npy”的文件。

不起作用的代码:

import re

files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]

regex = re.compile(r'_x\d+_y\d+\.npy')

selected_files = filter(regex.match, files)
print(selected_files)

同样的正则表达式在 Ruby 中也适用于我:

selected = files.select { |f| f =~ /_x\d+_y\d+\.npy/ }

Python 代码有什么问题?

最佳答案

selected_files = filter(regex.match, files)

re.match('regex')等于 re.search('^regex')text.startswith('regex') 但正则表达式版本。 它只检查字符串是否以正则表达式开头

所以,请改用 re.search():

import re

files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]

regex = re.compile(r'_x\d+_y\d+\.npy')

selected_files = list(filter(regex.search, files))
# The list call is only required in Python 3, since filter was changed to return a generator
print(selected_files)

输出:

['/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.npy']

如果您只想获取所有 .npy 文件,str.endswith()会是更好的选择:

files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]


selected_files = list(filter(lambda x: x.endswith('.npy'), files))

print(selected_files)

关于python - 使用 re.match 过滤字符串列表时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117950/

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