使用python查找txt fi中的重复名称

2024-06-01 07:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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

这种模式在今年剩下的时间里重复,我要做的是找到任何重叠的时间表。所以如果鲍勃@电子邮件在那个周末的不止一个日程表上,我想找到并打印出来。 示例:

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

谢谢,如果有什么问题请告诉我。你知道吗


Tags: ofre语言foremailresultjohn结构化
2条回答

您可以使用正则表达式创建集合的dict来执行以下操作:

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']}

我想你可以用地图来存储<name, list of schedule>,比如<bob@email, [Schedule1]>,当你度过每个周末的时候。每次要添加新项时,可以检查是否已经设置了密钥。如果是,则将该时间表添加到相应的列表中。如果否,则向该映射添加新项。然后,在打印时,只打印列表中具有多个计划的项目。你知道吗

对于Python,可以使用dictionary作为映射。 https://www.tutorialspoint.com/python/python_dictionary.htm

相关问题 更多 >