lolamontes69

Ch6 Ex5-Programming Collective Intelligence.

Jul 18th, 2013
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.02 KB | None | 0 0
  1. """ Chapter 6 Exercise 5: Preserving IP addresses.
  2.  
  3.    IP addresses, phone numbers, and other numerical information can be helpful in identifying spam. Modify the feature extraction function to return these items as features. (IP addresses have periods embedded in them, but you still need to get rid of the periods between sentences.)
  4.  
  5.    --Did this with regex.--
  6.    First one gets ip addys and phone numbers, the second gets ip addys from inside brackets.
  7.    Also added the variable word combos to this version. (In regular emails this adds more training time before it begins to recognize features: unless of course you add assumed probabilities to emails etc (:I'm considering implementing it:) )
  8. """
  9.  
  10. import poplib, email, string
  11. import getpass as getpass
  12. import re as re
  13.  
  14. # Adds intact emails, urls, ip addys and telephone numbers. Splits words by non-alpha, as singles and combos.
  15. def getwords(doc):
  16.  
  17.     wordnum=2
  18.     splitter=re.compile('\\W*')
  19.  
  20.     # The regular expressions for this exercise.
  21.     variousnumbers = re.findall(" [/(0-9/) -0-9]{11,25}", doc) + re.findall(r"[^[]*\[([^]]*)\]", doc)
  22.  
  23.     emails = re.findall("[\w.]+@[\w.]+", doc)
  24.     for a in range(len(emails)):  
  25.         if emails[a][-1] == '>':emails[a]= emails[a][:-1]
  26.     urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', doc)
  27.     for a in range(len(urls)):  
  28.         if urls[a][-1] == '>':urls[a]= urls[a][:-1]
  29.  
  30.     # So these are only added the one time.
  31.     for a in urls: doc = doc.replace(a," ")
  32.     for a in emails: doc = doc.replace(a," ")
  33.     for a in variousnumbers: doc = doc.replace(a," ")
  34.  
  35.     doc = ''.join(i for i in doc if not i.isdigit())
  36.     words=[s.lower() for s in splitter.split(doc) if len(s)>2 and len(s)<20]
  37.  
  38.     # Change wordnum for word combo length
  39.     for a in range(len(words)-wordnum+1):
  40.         phrases = ' '.join(words[a:a+wordnum])
  41.         words.append(phrases)
  42.  
  43.     # Put all the lists together and return a unique wordset
  44.     words = words + urls + emails + variousnumbers
  45.     return dict([(w,1) for w in words])
  46.  
  47. # Message is for reading, fulltext is for processing
  48. def read(message,fulltext,classifier):
  49.     print message
  50.     guess = str(classifier.classify(fulltext))  # Print the best guess at the current category
  51.     print '\nGuess: '+ guess
  52.  
  53.     cl=raw_input('Enter category: ')            # Ask the user to specify the correct category and train on that
  54.     if cl == "": cl = guess                     # If the guess is correct just press enter as a timesaver
  55.     classifier.train(fulltext,cl)
  56.  
  57. def get_mails(classifier):
  58.     # Made for usage with gmail.
  59.     username = str(raw_input('Enter username >'))          # 'recent:YOURUSERNAME' limits it to last months mail
  60.     password = getpass.getpass(prompt='Enter password >')
  61.  
  62.     mailserver = poplib.POP3_SSL('pop.gmail.com')
  63.     mailserver.user(username)                  
  64.     mailserver.pass_(password)
  65.     (numMsgs, totalSize) = mailserver.stat()               # Print some stats...
  66.     print "numMsgs =",numMsgs,"\ntotalSize =",totalSize
  67.     paused = raw_input('Press <ENTER> to continue')        # Dramatic pause
  68.  
  69.     numMessages = len(mailserver.list()[1])
  70.     for i in reversed(range(numMessages)):
  71.         fulltext = ""
  72.         message = "_________________________________\ni =" + str(i)
  73.         message += "\n_________________________________\n"
  74.         msg = mailserver.retr(i+1)
  75.         str1 = string.join(msg[1], "\n")
  76.         mail = email.message_from_string(str1)
  77.         try:
  78.             message += "From: " + mail["From"] + "\n" + "Subject: " + mail["Subject"] + "\n" + "Date: " + mail["Date"] + "\n"
  79.             fulltext += mail["From"] + " " + mail["Subject"] + " " + mail["Received"] + " "
  80.         except: pass
  81.         for part in mail.walk():
  82.             if part.get_content_type() == 'text/plain':
  83.                 message += "Body: " + part.get_payload()
  84.                 fulltext += part.get_payload()
  85.         read(message,fulltext,classifier)                # train the database
Advertisement
Add Comment
Please, Sign In to add comment