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

时间:2017-12-31 05:19:23

标签: 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)
        str1=i[x+1:y].strip()
        print str1
        count=count+1
print count

最终输出给了我句柄,但我可以删除重复的句柄,如果我打印uct.ac.za它不应该打印并再次计数

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

1 个答案:

答案 0 :(得分:1)

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

对于count,您可以使用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)
相关问题