<commit_before>#! /usr/local/bin/python
#-*- coding: utf-8 -*-

__author__ = "<NAME>"
__version__ = "$Revision: 0.8 $"
__date__ = "$Date: 2010/07/05 $"
__copyright__ = "Copyright (c) 2010 <NAME>"
__license__ = "GPLv3"

IMPORT_ERROR = []

import re
try:
    import pylab
except:
    IMPORT_ERROR.append("pylab")
import string
import hashlib
import sqlite3
import operator
import urlparse

import smtplib
from email.mime.text import MIMEText

import urllib2
from BeautifulSoup import BeautifulSoup

from datetime import datetime
from string import punctuation
from collections import Counter
from collections import OrderedDict

from StringIO import StringIO

try:
    from oice.langdet import langdet
    from oice.langdet import streams
    from oice.langdet import languages
except:
    IMPORT_ERROR.append("oice")

import threading
LOCKER = threading.Lock()

import os
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read("./cfg/pyAggr3g470r.cfg")
path = config.get('global','path')
sqlite_base = os.path.abspath(config.get('global', 'sqlitebase'))
mail_from = config.get('mail','mail_from')
mail_to = config.get('mail','mail_to')
smtp_server = config.get('mail','smtp')
username =  config.get('mail','username')
password =  config.get('mail','password')


def detect_language(text):
    """
    Detect the language of a text.
    English, French or other (not detected).
    """
    text = text.strip()
    try:
        text_stream = streams.Stream(StringIO(text))
        lang = langdet.LanguageDetector.detect(text_stream)
    except:
        return 'other'
    if lang == languages.french:
        return 'french'.encode('utf-8')
    elif lang == languages.english:
        return 'english'.encode('utf-8')
    else:
        return 'other'

def clear_string(data):
    """
    Clear a string by removing HTML tags, HTML special caracters
    and consecutive white spaces (more that one).
    """
    p = re.compile(r'<[^<]*?/?>')
    q = re.compile(r'&#[0-9]+;')
    r = re.compile(r's+')
    return p.sub('', q.sub('', r.sub('', data)))

def top_words(dic_articles, n=10, size=5):
    """
    Return the n most frequent words in a list.
    """
    words = {}
    articles_content = ""
    for rss_feed_id in dic_articles.keys():
        for article in dic_articles[rss_feed_id]:
            articles_content += clear_string(article[4].encode('utf-8'))

    words_gen = [word for word in articles_content.split() if len(word) > size]
    words_gen = [word.strip(punctuation).lower() for word in words_gen]

    words = Counter()
    for word in words_gen:
        words[word] += 1
    top_words = sorted(words.iteritems(),
                key=lambda(word, count): (-count, word))[:n]
    return top_words

def tag_cloud(tags):
    """
    Generates a tags cloud.
    """
    tags.sort(key=operator.itemgetter(0))
    return ' '.join([('<font size="%d"><a href="/q/?querystring=%s">%s</a></font>\n' % \
                    (min(1 + count * 7 / max([tag[1] for tag in tags]), 7), word, word)) \
                        for (word, count) in tags])<commit_msg>Use of most_common() method of collections.Counter() object (new in Python 2.7)<commit_after>#! /usr/local/bin/python
#-*- coding: utf-8 -*-

__author__ = "<NAME>"
__version__ = "$Revision: 0.8 $"
__date__ = "$Date: 2010/07/05 $"
__copyright__ = "Copyright (c) 2010 <NAME>"
__license__ = "GPLv3"

IMPORT_ERROR = []

import re
try:
    import pylab
except:
    IMPORT_ERROR.append("pylab")
import string
import hashlib
import sqlite3
import operator
import urlparse

import smtplib
from email.mime.text import MIMEText

import urllib2
from BeautifulSoup import BeautifulSoup

from datetime import datetime
from string import punctuation
from collections import Counter
from collections import OrderedDict

from StringIO import StringIO

try:
    from oice.langdet import langdet
    from oice.langdet import streams
    from oice.langdet import languages
except:
    IMPORT_ERROR.append("oice")

import threading
LOCKER = threading.Lock()

import os
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read("./cfg/pyAggr3g470r.cfg")
path = config.get('global','path')
sqlite_base = os.path.abspath(config.get('global', 'sqlitebase'))
mail_from = config.get('mail','mail_from')
mail_to = config.get('mail','mail_to')
smtp_server = config.get('mail','smtp')
username =  config.get('mail','username')
password =  config.get('mail','password')


def detect_language(text):
    """
    Detect the language of a text.
    English, French or other (not detected).
    """
    text = text.strip()
    try:
        text_stream = streams.Stream(StringIO(text))
        lang = langdet.LanguageDetector.detect(text_stream)
    except:
        return 'other'
    if lang == languages.french:
        return 'french'.encode('utf-8')
    elif lang == languages.english:
        return 'english'.encode('utf-8')
    else:
        return 'other'

def clear_string(data):
    """
    Clear a string by removing HTML tags, HTML special caracters
    and consecutive white spaces (more that one).
    """
    p = re.compile(r'<[^<]*?/?>')
    q = re.compile(r'&#[0-9]+;')
    r = re.compile(r's+')
    return p.sub('', q.sub('', r.sub('', data)))

def top_words(dic_articles, n=10, size=5):
    """
    Return the n most frequent words in a list.
    """
    articles_content = ""
    for rss_feed_id in dic_articles.keys():
        for article in dic_articles[rss_feed_id]:
            articles_content += clear_string(article[4].encode('utf-8'))

    words_gen = [word for word in articles_content.split() if len(word) > size]
    words_gen = [word.strip(punctuation).lower() for word in words_gen]

    words = Counter()
    for word in words_gen:
        words[word] += 1
    return words.most_common(n)

def tag_cloud(tags):
    """
    Generates a tags cloud.
    """
    tags.sort(key=operator.itemgetter(0))
    return ' '.join([('<font size="%d"><a href="/q/?querystring=%s">%s</a></font>\n' % \
                    (min(1 + count * 7 / max([tag[1] for tag in tags]), 7), word, word)) \
                        for (word, count) in tags])
{'fraction_non_alphanumeric': 0.14159725624693778, 'fraction_numerical': 0.012412216233872285, 'mean_word_length': 3.3868194842406876, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1282122', 'n_tokens_mistral': 2040, 'n_tokens_neox': 1966, 'n_words': 522}