Python 2.7 删除打印中重复的字符串值

Python 2.7 删除打印中重复的字符串值,python-2.7,Python 2.7,我想统计一下我使用以下代码发送邮件的不同大学: fname = raw_input('Enter the file name: ') try: fhan = open(fname) except: print 'File cannot be opened:', fname count = 0 sum = 0 for i in fhan: if i.startswith('From'): x=i.find('@') y=i.find(' ',x)

我想统计一下我使用以下代码发送邮件的不同大学:

fname = raw_input('Enter the file name: ')
try:
    fhan = open(fname)
except:
print 'File cannot be opened:', fname
count = 0
sum = 0
for i in fhan:
    if i.startswith('From'):
        x=i.find('@')
        y=i.find(' ',x)
        str1=i[x+1:y].strip()
        print str1
        count=count+1
print count
最终输出给我句柄,但我可以删除重复的句柄吗?如果我打印uct.ac.za,它不应该再次打印和计数


文件链接:www.py4inf.com/code/mbox short.txt

您可以将句柄附加到列表中,而不是打印它。然后将该列表转换为一个集合。在一个集合中,没有重复的元素,因此您将获得一组独特的大学。最后,您可以遍历集合并打印大学

对于计数,您可以使用len函数对集合中的大学进行计数

这是修改后的代码:-

fname = raw_input('Enter the file name: ')
try:
    fhan = open(fname)
except:
    print 'File cannot be opened:', fname
universities = []
for i in fhan:
    if i.startswith('From'):
        x=i.find('@')
        y=i.find(' ',x)
        str1=i[x+1:y].strip()
        universities.append(str1)
universities = set(universities)
for i in universities:
    print i
print len(universities)

欢迎来到SO!请编辑到您的问题中:您是否希望与之前的内容相比,不立即重复,或者需要以某种方式记住所有已打印的内容?