【问题标题】:Python how to match files to templatesPython如何将文件与模板匹配
【发布时间】:2013-01-07 04:56:28
【问题描述】:

我希望将许多文件与一些常用模板进行匹配,并提取差异。我想就最好的方法提出建议。例如:

模板 A:

<1000 text lines that have to match>
a=?
b=2
c=3
d=?
e=5
f=6
<more text>

模板 B:

<1000 different text lines that have to match>
h=20
i=21
j=?
<more text>
k=22
l=?
m=24
<more text>

如果我传入文件 C:

<1000 text lines that match A>
a=500
b=2
c=3
d=600
e=5
f=6
<more text>

我想用一种简单的方式说这匹配模板 A,并提取 'a=500'、'd=600'。

我可以将这些与正则表达式匹配,但文件相当大,构建该正则表达式会很痛苦。

我也尝试过 difflib,但解析操作码并提取差异似乎不是最佳选择。

谁有更好的建议?

【问题讨论】:

    标签: python


    【解决方案1】:

    您可能需要稍微调整一下才能处理额外的文本,因为我不知道确切的格式,但应该不会太难。

    with open('templ.txt') as templ, open('in.txt') as f:
        items = [i.strip().split('=')[0] for i in templ if '=?' in i]
        d = dict(i.strip().split('=') for i in f)
        print [(i,d[i]) for i in items if i in d]
    

    出局:

    [('a', '500'), ('d', '600')]  # With template A
    []                            # With template B
    

    或者如果对齐:

    from itertools import imap,compress
    with open('templ.txt') as templ, open('in.txt') as f:
        print list(imap(str.strip,compress(f,imap(lambda x: '=?' in x,templ))))  
    

    出局:

    ['a=500', 'd=600']
    

    【讨论】:

    • 先谢谢,这是我没想到的数据提取方法。不过,它似乎无助于找到匹配的模板。如果我在 templ.txt 设置为模板 B 的情况下运行它,那么我会得到 ['c=3', 'e=5']。我正在寻找一种方法来遍历模板,找到匹配的模板,然后提取数据。
    • @PeterHofmann -- 添加了一个可以使用任何模板的模板。
    【解决方案2】:

    不考虑性能:

    1. 将所有内容加载到字典中,例如A = {'a': '?', 'b': 2, ...}B = {'h': 20, 'i': 21, ...}C = {'a': 500, 'b': 2, ...}

    2. 如果 A.keys() == C.keys() 你知道 C 匹配 A。

    3. 那么只需diff both dictionaries

    根据需要改进。

    【讨论】:

    • 抱歉,我应该让我的示例更清楚,文件中不仅仅是值,还有静态行、cmets 以及许多其他应该匹配的东西。
    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    相关资源
    最近更新 更多