Skip to main content
 首页 » 编程设计

python之使用python查找txt文件中重复的名字

2025年02月15日14qlqwjy

我想使用 python(尽管任何语言都可以)来查看如下所示的结构化文本文件:

========= Weekend of 2016-12-02: ================ 
Schedule1: 
bob@email 
Schedule2: 
john@email 
bob@email 
Schedule3: 
Terry@email 
========= Weekend of 2016-12-09: ================ 
Schedule1: 
jake@email 
Schedule2: 
mike@email 
bob@email 
Schedule3: 
howard@email 

这种模式在今年余下的时间里重复出现,我想要完成的是找到任何重叠的时间表。因此,如果 bob@email 在那个周末有多个时间表,我想找到并打印出来。 示例:

Overlaps found for: 
========= Weekend of 2016-12-02: ================ 
bob@email is scheduled for schedule1, and schedule2. 

因为这是唯一的重叠,所以这是唯一会打印的事件,如果有更多重叠,那么它们将以相同的格式打印在彼此下面。 有什么办法可以做到这一点?

到目前为止我找到的代码允许我找到每个周末并打印出来,但是我不确定如何更详细地查看内容。

import re 
    def compare(): 
         with open("weekends.txt","r") as fp: 
             for result in re.findall('Weekend of (.*?):', fp.read(), re.S): 
                 print(result) 

这产生了

2016-12-02 
2016-12-09 

谢谢,如果有任何问题,请告诉我。

请您参考如下方法:

你可以用正则表达式创建集合字典来做这样的事情:

import re 
from collections import Counter 
 
data={} 
 
with open(fn) as f_in: 
    txt=f_in.read() 
 
for block in re.finditer(r'^=+\s+([^:]+:)\s=+\s+([^=]+)', txt, re.M): 
    di={} 
    for sc in re.finditer(r'^(Schedule\s*\d+):\s*([\s\S]+?)(?=(?:^Schedule\s*\d+)|\Z)', block.group(2), re.M): 
        di[sc.group(1)]=set(sc.group(2).splitlines()) 
    data[block.group(1)]=di 
 
for date, DofS in data.items(): 
    c=Counter() 
    for s in DofS.values(): 
        c+=Counter(s) 
    inverted={k:[] for k, v in c.items() if v>1}  
    if not inverted: 
        continue 
    print date   
    for k in DofS: 
        for e in DofS[k]: 
            if e in inverted: 
                inverted[e].append(k)     
    print "\t",inverted      

打印:

Weekend of 2016-12-02: 
    {'bob@email': ['Schedule1', 'Schedule2']}