【问题标题】:Python - Loop through list within regexPython - 遍历正则表达式中的列表
【发布时间】:2013-08-28 22:09:50
【问题描述】:

是的,我对 Python 比较陌生,您可能会在我的代码中看到这一点,但是有没有办法在正则表达式中遍历列表?

基本上,我正在遍历文件夹中的每个文件名,从文件名中获取一个代码(2-6 位),我想将它与文本文件中的代码列表进行比较,该列表具有附加名称,格式为“1234_Name”(不带引号)。如果代码在两个列表中都存在,我想打印出列表条目,即 1234_Name。目前我的代码似乎只查看文本文件列表中的第一个条目,我不知道如何让它通过它们来查找匹配项。

import os, re

sitesfile = open('C:/Users/me/My Documents/WORK_PYTHON/Renaming/testnames.txt', 'r')
filefolder = r'C:/Users/me/My Documents/WORK_PYTHON/Renaming/files/'

sites = sitesfile.read()
site_split = re.split('\n', sites)


old = []
newname = []

for site in site_split:
    newname.append(site)


for root, dirs, filenames in os.walk(filefolder):
    for filename in filenames:
        fullpath = os.path.join(root, filename)
        filename_split = os.path.splitext(fullpath) 
        filename_zero, fileext = filename_split
        filename_zs = re.split("/", filename_zero)
        filenm = re.search(r"[\w]+", str(filename_zs[-1:]))#get only filename, not path
        filenmgrp = filenm.group()

        pacode = re.search('\d\d+', filenmgrp)
        if pacode:
            pacodegrp = pacode.group()
            match = re.match(pacodegrp, site)
            if match:
                 print site

希望这是有道理的 - 提前非常感谢!

【问题讨论】:

    标签: python regex python-2.7 for-loop


    【解决方案1】:

    因此,请改用以下代码:

    import os
    import re
    def locate(pattern = r'\d+[_]', root=os.curdir):
        for path, dirs, files in os.walk(os.path.abspath(root)):
            for filename in re.findall(pattern, ' '.join(files)):
                yield os.path.join(path, filename)
    

    ..这只会返回与给定正则表达式模式匹配的文件夹中的文件。

    with open('list_file.txt', 'r') as f:
         lines = [x.split('_')[0] for x in f.readlines()]
    
    print_out = []
    
    for f in locate(<your code regex>, <your directory>):
        if f in lines: print_out.append(f)
    
    print(print_out)
    

    ...首先在您的 list_file 中找到有效代码,然后将返回的文件与您给定的正则表达式进行比较。

    【讨论】:

    • fnmatch.filter 接受正则表达式吗?我以为它只接受 unix 风格的 glob。
    • 啊,你是对的。从我的 funcs.py 中挖出来 :) 我仍然认为它可以满足他想要做的事情,只是格式略有不同。请参阅此处了解可接受的模式匹配,docs.python.org/2/library/fnmatch.html
    • 我似乎无法将任何内容添加到字符串列表中。当我在寻找数字时,'[0123456789]' 不应该工作吗?
    • 很抱歉,我仍然没有得到任何附加到 print_out 的内容。我觉得我已经尝试了 中所有内容的每一种组合。你介意建议它应该是什么样子,特别是正则表达式应该搜索什么字符串?为自己的愚蠢道歉。
    • 没问题,伙计 :) 对文件夹或某些文件进行屏幕截图,其中包含您想要的某些文件与您不想要的其他文件匹配,我们可以提出一个正则表达式。也许也包括文件中的一个样本,其中包含可接受的数字。然后我们可以清理您的“是否存在,是否存在”逻辑并使其工作。您可以使用 pastebin 或发送电子邮件至 blakev@null.net
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2012-09-02
    • 2017-01-01
    • 2023-03-25
    • 2018-04-26
    • 1970-01-01
    相关资源
    最近更新 更多