【问题标题】:fnmatch how exactly do you implement the match any chars in seq patternfnmatch 你如何实现匹配 seq 模式中的任何字符
【发布时间】:2011-09-24 21:16:20
【问题描述】:

所以我有一个 os.walk 代码

search = self.search.get_text()
top = '/home/bludiescript/tv-shows'
for dirpath, dirnames, filenames in os.walk(top):
  for filename in filenames:
    if fnmatch.fnmatch(filename, search)
      print os.path.join([dirpath, filename])

在 python 文档上,它显示您可以将任何字符序列与 [seq] 模式匹配,但无论我如何尝试实现它都会给出如此错误或根本没有结果。

那么在搜索中匹配汽车序列的正确实现是什么,以便打印出匹配的文件或文件

我尝试过的实现

if fnmatch.fnmatch(filename, [search]) error i got was typeerror unhasable type : 'list'
if fnmatch.fnmatch[filename, search] error i got was typeerror fnmatch function is not subscriptable
if fnmatch.fnmatch([filename, search]) error typeerror fnmatch takes two arguments  1 given
if fnmatch.fnmatch([filename], search) error typeerror expected string or buffer
if fnmatch.fnmatch([search], filename) error typeerror expected string or buffer 
if fnmatch.fnmatch(filename, search, [seq]) error nameerror global name seq not defined

if fnmatch.fnmatch(filename, '[search]')

没有错误,但没有产生任何结果

搜索值

你好,mkv,merry 1、2、3、4、5、6、7等……

【问题讨论】:

  • 你用过什么样的模式?您看到的错误是什么?
  • 我编辑了这个问题来回答你的问题
  • 您能否向我们展示您用于 search 的值的具体示例?另外,请编辑问题,使其可读。
  • 我让我的搜索值保持简单,以便我知道至少一个文件会出现在结果中,例如 hello、mkv、merry 等。我尝试使用在一个数字中多次出现的东西的文件,所以它应该产生至少一个结果,如果不是更多

标签: python search os.walk


【解决方案1】:

fnmatch 实现了 Unix shell 通配符语法。因此,无论您在ls 命令中输入什么(例如)都可以:

>>> fnmatch.fnmatch("qxx", "[a-z]xx")
True
>>> fnmatch.fnmatch("abc", "a??")
True
>>> fnmatch.fnmatch("abcdef", "a*f")
True
>>> fnmatch.fnmatch("abcdef", "a*[f-k]")
True

请记住,fnmatch 是纯粹的字符串匹配操作。如果您发现使用不同的模式样式(例如正则表达式)更方便,那么只需使用正则表达式操作来匹配您的文件名。

【讨论】:

  • 非常感谢您将我指向正则表达式 re.findall 是我正在寻找的。我还发现它区分大小写,我没有意识到。
猜你喜欢
  • 2010-10-18
  • 2022-11-02
  • 2019-05-26
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2012-08-22
  • 2021-12-09
相关资源
最近更新 更多