2015-07-09 3 views
0

У меня есть мульти-строки писем, и мне нужно сделать пару вещей:Добавление нескольких строк в один список?

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
... etc 
  1. мне нужно поставить их в один список: ['[email protected]','[email protected]','[email protected]' ..etc ]
  2. необходимо выяснить который по электронной почте является самым повторяющимся в этом списке. Вот как я начал свой код, и я надеюсь, что смогу завершить его, с того момента, как я закончил свой код!

    fname = raw_input("Enter file name: ") 
    if len(fname) < 1 : fname = "mbox-short.txt" 
    fh = open(fname) 
    lines = [] 
    count = 0 # For next step 
    for line in fh: 
        line = line.rstrip() 
        if not line.startswith("From ") : continue 
        x = line.split() 
        emails = x[1] 
    #print y 
    
    maxapperence = 0 
    famous = None 
    for mail in emails: 
        count = emails.count(mail) 
        if count > maxapperence: 
         famous = mail 
    print famous 
    
    apparence = dict() 
    for mail in set(emails): 
        apparence[mail] = emails.count(mail) 
    print apparence] 
    

    вне положенный:

    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    [email protected] 
    
+0

Проверить http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python – nucleon

+2

Посмотрите на 'collections.Counter' https://docs.python.org/2/library/collections.html – NightShadeQueen

ответ

1

Если у вас есть файл, который содержит только адреса электронной почты:

import collections 
filename = '' 
c = collections.Counter(map(str.strip, open(filename).readlines())) 
print(c.most_common(10)) # dumb example of possible output format 
+0

Удивительный помощник по ответам – The6thSense

+0

Простите, может быть, я должен был сказать это с самого начала, но на самом деле я извлек эти адреса электронной почты из файла txt! – Khalida

+0

@ Khalida Если у вас уже есть адреса электронной почты в списке, вы можете заменить «map (....)» в моем примере на свой список: 'l = ['[email protected]', [email protected] «]; c = collections.Counter (l) ' – chelmertz

0

Первый пример

emails = """[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected]""".split("\n") 

maxapperence = 0 
famous = None 
for mail in set(emails): 
    count = emails.count(mail) 
    if count > maxapperence: 
     famous = mail 
     maxapperence = count 
print famous, maxapperence 

Вы также можете хранить всю почту apparence

apparence = dict() 
for mail in set(emails): 
    apparence[mail] = emails.count(mail) 
print apparence 
+0

Я сохранил все электронные письма в 'y' – Khalida

+0

Привет, wilfriedrt, я очень близко, мне просто нужно показать количество раз, что Email существует в этом списке, на момент выставления: cwen @ iupui.edu, в то время как это должно быть: [email protected] 5, поскольку Email существует 5 раз в этом списке, я попытался использовать count = 0 в том же цикле, но он не прошел цикл! пожалуйста помоги . – Khalida

+0

Вам просто нужно использовать maxappereance, поскольку он используется для хранения максимального количества явлений. – wilfriedrt

Смежные вопросы