【问题标题】:Storing strings into list from Python regex over a file通过文件将字符串从 Python 正则表达式存储到列表中
【发布时间】:2015-02-19 02:32:23
【问题描述】:

我正在使用 Python 的正则表达式从文件中提取路径,然后尝试将路径附加到单个列表中。路径在文件 (options) 的不同行中指定如下:

EXE_INC = \
    -I$(LIB_SRC)/me/bMesh/lnInclude \
    -I$(LIB_SRC)/mTools/lnInclude \
    -I$(LIB_SRC)/dynamicM/lnInclude

我的功能是:

def libinclude():
with open('options', 'r') as options:
    for lines in options:
        if 'LIB_SRC' in lines:
            result = []
            lib_src_path = re.search(r'\s*-I\$\(LIB_SRC\)(?P<lpath>\/.*)', lines.strip())
            lib_path = lib_src_path.group(1).split()
            result.append(lib_path[0])
            print result
return (result)

我得到的输出是:

['/me/bMesh/lnInclude']
['/mTools/lnInclude']
['/dynamicM/lnInclude']

但是,如您所见,我得到了三个不同的列表,每个列表都是针对文件中的一行获得的,options。有没有办法在一个列表中获取这三个路径,以便在函数之外可以使用这些值。

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    当然,每次找到匹配项时,您都会创建一个新列表。所以只创建一个列表,每次找到匹配项时继续追加它

    def libinclude():
    with open('options', 'r') as options:
        result = []
        for lines in options:
            if 'LIB_SRC' in lines:
                lib_src_path = re.search(r'\s*-I\$\(LIB_SRC\)(?P<lpath>\/.*)', lines.strip())
                lib_path = lib_src_path.group(1).split()
                result.append(lib_path[0])
                print result
    

    【讨论】:

    • 谢谢@Greg。确实微不足道!
    猜你喜欢
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2014-08-10
    相关资源
    最近更新 更多