...
 
Commits (4)
This diff could not be displayed because it is too large.
#!/usr/bin/env/ python
# This script automatises the following Oulipo constraint:
# http://oulipo.net/fr/contraintes/litterature-definitionnelle
# The output is printed in a txt-file and in a Logbook in Context
# Copyright (C) 2016 Constant, Algolit, An Mertens
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details: <http://www.gnu.org/licenses/>.
from __future__ import division
import nltk
from nltk.corpus import wordnet as wn
from pattern.en import tag
import nltk.data
from random import shuffle, choice
# VARIABLES
# textfiles
source = open("frankenstein_for_machines.txt", 'r')
destination = open("litterature_definitionelle.txt", "wt")
## SCRIPT
# select 4 sentences from source
## split source text into list of sentences
finding_sentences = nltk.data.load('tokenizers/punkt/english.pickle')
sentences_list = []
with source as text:
for line in text:
# this returns a list with 1 element containing the entire text, sentences separated by \n
sentences = '\n'.join(finding_sentences.tokenize(line.strip()))
# transform string into list of sentences
sentences_list = sentences.split("\n")
# pick 4 random sentences
selected_sentences = []
number = 0
while number < 5:
selected_sentences.append(choice(sentences_list))
number += 1
# tokenize source and get Part-of-Speech tags for each word
definitions = []
for sentence in selected_sentences:
# create tuple of tuples with pairs of word + POS-tag
collection = tag(sentence, tokenize=True, encoding='utf-8')
# transform tuple into list to be able to manipulate it
collection = list(collection)
# for each pair:
for element in collection:
# look for nouns & replace them with their definition
if element[1] == "NN":
if wn.synsets(element[0]):
synset = wn.synsets(element[0])
definitions.append("<")
definitions.append(synset[0].definition())
definitions.append(">")
else:
break
else:
# non-nouns are left as words
definitions.append(element[0])
# write the transformed sentence
#print(" ".join(definitions))
with destination as text:
text.write("ORIGINAL TEXT\n\n\n")
for sentence in selected_sentences:
text.write(sentence+"\n")
text.write("\n\n")
text.write("\n\nLITTERATURE DEFINITIONELLE\n\n\n")
text.write(" ".join(definitions))
# close the text file
source.close()
destination.close()
# -------------------------------------------
# # Write in logbook
# # print chapters
# #writetologbook('\setuppagenumber[state=start]')
# writetologbook('\n\section{LITTERATURE DEFINITIONELLE}\n')
# # print_sentences(spring_chapter)
# writetologbook('\nORIGINAL TEXT\crlf\crlf\n')
# for sentence in selected_sentences:
# writetologbook(sentence+"\n")
# writetologbook("\crlf\crlf\n\n\n")
# writetologbook('\nLITTERATURE DEFINITIONELLE\crlf\crlf\n')
# writetologbook(" ".join(definitions))
\ No newline at end of file
ORIGINAL TEXT
Begone, or let us try our strength in a fight, in which one must fall.
Yet even thus I loved them to adoration; and to save them, I resolved to dedicate myself to my most abhorred task.
Almost spent, as I was, by fatigue and the dreadful suspense I endured for several hours, this sudden certainty of life rushed like a flood of warm joy to my heart, and tears gushed from my eyes.
But even human sympathies were not sufficient to satisfy his eager mind.
And why should I describe a sorrow which all have felt, and must feel?
LITTERATURE DEFINITIONELLE
Begone , or let us try our < the property of being physically or mentally strong > in a < a hostile meeting of opposing military forces in the course of a war > , in which one must fall . Yet even thus I loved them to < a feeling of profound love and admiration > ; and to save them , I resolved to dedicate myself to my most abhorred < any piece of work that is undertaken or attempted > . Almost spent , as I was , by < temporary loss of strength and energy resulting from hard physical or mental work > and the dreadful < apprehension about what is going to happen > I endured for several hours , this sudden < the state of being certain > of < a characteristic state or mode of living > rushed like a < the rising of a body of water and its overflowing onto normally dry land > of warm < the emotion of great happiness > to my < the locus of feelings and intuitions > , and tears gushed from my eyes . But even human sympathies were not sufficient to satisfy his eager < that which is responsible for one's thoughts and feelings; the seat of the faculty of reason > . And why should I describe a < an emotion of great sadness associated with loss or bereavement > which all have felt , and must feel ?
\ No newline at end of file
gitolite-admin @ 3f279207
Subproject commit 3f279207d39f5499bb5431d408b4f19bb0bf615f
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from random import *
import nltk
import time
from random import shuffle
# Year is name of the containing folder
year = '1941'
now = time.strftime("%Y-%m-%d_%H:%M:%S")
filename = year+'_'+now+'.txt'
random_author = ""
duo = []
author_texts = []
texts = []
spring_chapter=[]
summer_chapter=[]
autumn_chapter=[]
winter_chapter=[]
spring_select = []
summer_select = []
autumn_select = []
winter_select = []
def writetoLog(content):
try:
logfile = open(filename, "a")
try:
logfile.write(content)
finally:
logfile.close()
except IOError:
pass
# Make list of authors based on folder names
authors = os.listdir(year)
# Select a random duo of two authors (no repeats), and select one random text per author
i = 0
while i < 2:
if authors != []:
pos = randrange(len(authors))
random_author = authors[pos]
authors[pos] = authors[-1]
del authors[-1]
duo.append(random_author)
i += 1
for author in duo:
path = year+"/"+author
author_texts = os.listdir(path)
pos = randrange(len(author_texts))
random_text = path+"/"+author_texts[pos]
texts.append(random_text)
# Seasonal keywords
spring = ['birth','butterfly','flower','energy', 'breakthrough', 'sprawl', 'toddler', 'grow', 'plasticine', 'toy', 'hope', 'teenager', 'puberty', 'adolescence', 'sneakers', 'acne', 'pimple', 'jitters', 'first time', 'slang', 'verdant', 'leafy', 'juvenile', 'inexperienced', 'girlish', 'young', 'verginal', 'ingenuous', 'naive', 'innocent', 'launch', 'genesis', 'youth', 'vibration', 'dynamic', 'dynamism', 'vibrance', 'empowerment', 'enhancement', 'innovation', 'invention', 'play', 'await', 'blessing', 'fresh', 'small', 'spring', 'morning', 'sunrise', 'dawn']
summer = ['sun', 'heat', 'growth','expansion', 'develop', 'unfold', 'radiance', 'attempt', 'succeed', 'stumble', 'bloom', 'blossom', 'light', 'persistence', 'grace', 'mature' , 'strength' , 'method', 'serendipity', 'success', 'summit', 'zenith', 'glory', 'grandeur', 'splendor', 'belle epoque', 'power', 'bright', 'ripe', 'summer', 'rose', 'harmony', 'midday', 'full', 'birds', 'fashion', 'class', 'winner', 'victory', 'triumph', 'realization', 'diamond', 'precious', 'excitement', 'gold', 'beauty', 'fire']
autumn = ['leaves', 'decay', 'grey', 'gray','age','generation', 'calmness', 'sofa', 'pipe', 'mist','memory', 'remembrance', 'nostalgia', 'picture', 'cigar', 'painting', 'museum','indian summer', 'peace', 'sharing', 'teaching', 'harvest', 'slow', 'stiff', 'waste', 'autumn', 'sunset', 'dusk', 'evening', 'shadow', 'gloaming', 'twilight', 'feather', 'quiet', 'serenity', 'stillness', 'tranquility', 'rest', 'relaxed', 'silence', 'library', 'thought', 'experience', 'wise', 'wisdom', 'reflective', 'literate', 'serious']
winter = ['death', 'ice', 'cold','illness', 'death', 'ruin', 'decay', 'medicine', 'pus', 'infection', 'virus', 'nurse', 'hospital','funeral', 'coffin', 'soil', 'rat', 'skull', 'bones', 'skeleton','humus', 'transformation', 'symbiosis', 'seed', 'egg', 'offspring', 'sprout', 'pain', 'deteriorate', 'regress', 'retrogress', 'return', 'alter', 'change', 'metamorphose', 'modify', 'mutate', 'transfigure', 'transform', 'transmute', 'winter', 'snow', 'night', 'hell', 'heaven', 'earth','archives', 'replica', 'sorrow', 'grief', 'old']
# Select 20 random keywords from seasonal lists
i = 0
while i < 10:
if spring != []:
pos = randrange(len(spring))
word = spring[pos]
spring[pos] = spring[-1]
del spring[-1]
spring_select.append(word)
i += 1
i = 0
while i < 10:
if summer != []:
pos = randrange(len(summer))
word = summer[pos]
summer[pos] = summer[-1]
del summer[-1]
summer_select.append(word)
i += 1
i = 0
while i < 10:
if autumn != []:
pos = randrange(len(autumn))
word = autumn[pos]
autumn[pos] = autumn[-1]
del autumn[-1]
autumn_select.append(word)
i += 1
i = 0
while i < 10:
if winter != []:
pos = randrange(len(winter))
word = winter[pos]
winter[pos] = winter[-1]
del winter[-1]
winter_select.append(word)
i += 1
# Open all files and do basic cleanup
for source in texts:
text = open(source, 'r')
text = text.read()
text = text.replace("\r\n", " ")
text = text.replace("\r", " ")
text = text.replace("\n", " ")
text = text.replace(" ", " ")
# Split text into sentences with help of nltk
sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle')
sentences = sent_tokenizer.tokenize(text)
# Split each element of sentences into list of words
for sentence in sentences:
list = sentence.split(" ")
for word in list:
# Check if sentence contains a seasonal keyword, generate fake paragraps and combine sentences into chapters
i = 0
if word in spring_select:
i += 1
sentence = sentence+' '
if i == randint(1,6):
sentence = sentence+"\n\n"
i = 0
spring_chapter.append(sentence)
if word in summer_select:
i += 1
sentence = sentence+' '
if i == randint(1,6):
sentence = sentence+"\n\n"
i = 0
summer_chapter.append(sentence)
if word in autumn_select:
i += 1
sentence = sentence+' '
if i == randint(1,6):
sentence = sentence+"\n\n"
i = 0
autumn_chapter.append(sentence)
if word in winter_select:
i += 1
sentence = sentence+' '
if i == randint(1,6):
sentence = sentence+"\n\n"
i = 0
winter_chapter.append(sentence)
# Mix sentences
shuffle(spring_chapter)
shuffle(summer_chapter)
shuffle(autumn_chapter)
shuffle(winter_chapter)
# Open file and write book
author_duo = (str(duo[0])+' & '+str(duo[1])).replace("_", " ")
writetoLog('The Death of the Authors\n')
writetoLog(author_duo+'\n')
writetoLog('& Their Return to Life in Four Seasons\n')
writetoLog('A Constant Remix\n\n\n')
# Print chapter
writetoLog('\n\n\nSpring\n\n')
# Open file and add sentences
for sentence in spring_chapter:
writetoLog(sentence)
# Print chapter
writetoLog('\n\n\nSummer\n\n')
# Open file and add sentences
for sentence in summer_chapter:
writetoLog(sentence)
# Print chapter
writetoLog('\n\n\nAutumn\n\n')
# Open file and add sentences
for sentence in autumn_chapter:
writetoLog(sentence)
# Print chapter
writetoLog('\n\n\nWinter\n\n')
# Open file and add sentences
for sentence in winter_chapter:
writetoLog(sentence)
# Open file and add sources
writetoLog("\n\n\nColophon\n\n")
writetoLog("Sources:\n")
for text in texts:
credits = open(text,'r').readlines()[:1]
for credit in credits:
writetoLog(credit+'\n ')
writetoLog('This book was generated on '+now+' from sources available in the Public Domain as of '+str(int(year) + 71)+', 70 years after the death of '+author_duo+'.\n\nRead more at:\nwww.publicdomainday.org\nwww.constantvzw.org/publicdomainday')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import nltk
import treetaggerwrapper
import pickle
import codecs
#import pickle pour bien décoder en utf-8 le fichier sinon TreeTagger hurle
# classes et fonction d'affichage du TreeTaggerWrapper
# source: http://www.fabienpoulard.info/post/2011/01/09/Python-et-Tree-Tagger
class TreeTaggerWord:
def __init__(self, triplet):
self.word,self.postag,self.lemma = triplet
def formatTTG(output):
words = []
for w in output:
words.append(TreeTaggerWord(w.split("\t")))
return words
# fonction perso dérivée de formatTTG(output)
def wordCountTTG(output):
wordCount = 0
for w in output:
wordCount += 1
return wordCount
#TODO
# insérer une commande readline demandant si on veut:
# 1/ ouvrir un fichier 2/ saisir un texte
# 3/ si on affiche la sortie 4/ si on sort dans un fichier
#initialisation du dictionnaire et de la contrainte
mots_numerotes = {}
contrainte = int(7)
#début du programme lui-même : on charge un fichier
fichier = open("queneau_source.txt", 'r')
texteBrut = fichier.read().decode('utf-8')
fichier.close()
# on colle des étiquettes dans une variable nommée texte
tagger = treetaggerwrapper.TreeTagger(TAGLANG='fr',TAGDIR='/usr/share/treetagger',TAGINENC='utf-8',TAGOUTENC='utf-8')
textePOS = formatTTG(tagger.TagText(texteBrut))
#on duplique texte pour effectuer les traitements dans une copie
texteContraint = textePOS
#extraction des positions des substantifs dans une liste
nombreMots = wordCountTTG(tagger.TagText(texteBrut))
print "nombre de mots: " + str(nombreMots)
listeSubstantifs = []
for i in range(len(textePOS)):
if textePOS[i].postag == "NOM":
listeSubstantifs.append(int(i))
#oncrée_unelistecontraintedessunstatifs_car_laforme_\
#textePOS[listeContrainteSubstantifs[l+contrainte]].word_généèreuneerreurdetypage
listeContrainteSubstantifs = [int(x+contrainte) for x in listeSubstantifs]
TODO appliquer le décalage à la liste de positions pas aux positions dans le texte
# on remplace les substantifs par position & on les remplace dans le texte
# contraint par le mot situé position + contrainte
for l in range(len(listeSubstantifs)):
if l < len(listeSubstantifs) - contrainte:
texteContraint[listeSubstantifs[l]].word = (textePOS[listeSubstantifs[l+contrainte]].word).encode("utf-8")
print str(texteContraint[listeSubstantifs[l]]) + " VS " + str(textePOS[listeSubstantifs[l]])
else:
pass
# on recolle ensemble les mots du texte contraint dans un fichier de sortie
# en utilisant la syntaxe des lists comprehensions (listcomps)
#listeSortie = [texteContraint[x].word for x in range(nombreMots)]
fichierContraint = codecs.open("sortie.txt", "w", "utf-8")
sortieContrainte = ''
listeSortie = ''
exceptions = set(",;.\(")
for string in listeSortie:
#print string
if string in exceptions :
sortieContrainte += string
elif string == 'Attendu':
sortieContrainte += "\n" + string + " "
else:
sortieContrainte += string + " "
#print "sortieContrainte : " + sortieContrainte
fichierContraint.write(sortieContrainte)
fichierContraint.close()
#!/usr/bin/env python
# -*- coding: utf8 -*-
from codecs import encode, decode
print "\n###########################################################\n# #\n# ROT13 is NOT fun! #\n# #\n###########################################################"
def rotatif(source):
source = unicode(source,"utf8")
print "type de saisie : "
print type(source)
# on continue
sortie = encode(source, "rot13")
sortie = unicode(decode(sortie, "iso-8859-1"))
print "type de sortie : "
print type(sortie)
return sortie
while 1:
print rotatif(raw_input(u"\nSaisissez une phrase : "))
#bug en cas de caractères non-ASCII
#!/usr/bin/env python
# -*- coding: utf8 -*-
from codecs import encode, decode
print "\n###########################################################\n# #\n# ROT13 is NOT fun! #\n# #\n###########################################################\n"
print "Ctrl+c pour quitter le programme.\n"
def rotatif(source):
"""encode en ROT13 une chaîne et la recrache en utf-8"""
source = unicode(source,"utf8")
sortie = encode(source, "rot13")
#rot13 recrache toujours un string, on doit donc décoder & réencoder en UTF-8
sortie = "\n"+unicode(decode(sortie, "iso-8859-15"))
return sortie
try:
while 1:
print rotatif(raw_input(u"\nSaisissez une phrase : "))
except KeyboardInterrupt:
print "\n\nTot later!\n"
pass
#TODO if __name__ == __main__ thingie
Mercredi Semaine 2
fait du jour #1:
à 6h du matin, l'église en contrebas résonne déjà des gospels
fait du jour #2:
A 7h du matin, il fait grand jour sous la brume. L'enfant de la voisine hurle plus fort sous la garcette.
Dimanche S1
On pourrait croire le dimanche un jour tranquille. Les plus gros générateurs s'allument pour alimenter les hauts-parleurs des prêcheurs des églises plantées tous les 150m.
Jeudi S1
On pourrait croire que les coupures régulières de courant soient signe de tranquillité. Ah! le générateur Diesel vient de démarrer. Ah! Il s'éteint. Ah! Le backup essence vient de démarrer.
Churches
(Poétry sélective)
Clichés
On pourrait croire que le son de l'Afrique, ce sont de grands fauves rugissant dans la nuit et le son des tam-tam. C'est le balai des femmes qui balaient la cour au petit matin.
Politique? Gouvernance? Profit?
L'état fédéral a fait construire à Abuja un hotel destiné à accueillir les parlementaires venus des 4 coisn du pays. Une fois bâti (sur des fonds publics), il a été vendu au président dudit Parlement.
Société. Progrès.
Bien qu'ancienne colonie anglaise (18??-1960), le Nigéria roule à droite, et mesure en unités métriques. Par contre, eux non plus n'ont pas souhaité entrer dans la zone Euro.
Jardinage. Compound
Yam. Bitter leaves. Sweet leaves. Ground nut? Plantain. Pineapple. Mango. Cajasol. Wild mango. Manioc. Cough leave. Taro (cocoyam). Palm tree. Coconut tree. Merci!
Langues. Société
D'après un locuteur pidgin, cette langue serait née dans les colonies d'Amérique inventée par les esclaves afin de ne pas être compris de leurs maîtres. Ces mêmes esclaves, une fois émancipés, seraient revenus en Afrique, et l'auraient transmis aux locaux, ce qui expliquerait la relative homogénéité du pidgin en Afrique de l'Ouest, de la Sierra-Leone au Nigeria. Hmmm.... Affaire à suivre.
Langues.Agronomie.Gastronomie
Alors que le Britannique consommera des peanuts (cacahuètes), le locuteur pidgin préfère parler de ground nut (noix du sol littéralement), qu'il prononcera granut ; il mangera goulûment de la banane accompagnée de ces arachides torréfiées.
Santé. Plantes.
Au quotidien: 3 gélules de Veratrum Album 9CH au lever.
Dès la 1ère selle non moulée: 1 dose de Paratyphoïdium 15CH et Arsenicum Album 15ch 2x/jour. Merci.
Langues. Less is more
Sis & bro will agree, aucun locuteur n'a attendu bit.ly pour raccourcir ses UL.
Langues. Zoologie. Less is more
#!/bin/sh
#This script has been created by sound & net artist Andre Castro: http://www.andrecastro.info
#needs: pdftk, imagemagick and tesseract-ocr
#pdf should be 300dpi or higher resolution
pdftk $1 burst #splits a pdf document into single pages named pg_0*.pdf
#convert each pdf page
#1:from pdf to 8bit 300dpi tifs # this takes a while
for i in pg*.pdf
do
convert -units pixelsperinch -density 300x300 -colorspace Gray -depth 8 $i "`basename $i .p\
df`.tif"
done;
#2:from gray-scale tif to monochorome tif
for i in pg*.tif
do
convert $i +dither -monochrome -normalize "`basename $i .tif`-m.tif"
done;
#3:character recognition with tesseract
for i in *-m.tif
do
tesseract $i "`basename $i .tif`"
done;
#4: cat ocr text content under 1 file
DUMP=`basename $1 .pdf`.txt;#replace sufix .pdf to .txt
echo ==== $DUMP is the file with text content ====;
touch $DUMP; #create a new txt file
cat pg*.txt >> $DUMP;
#5: garbage collect
echo ==== moving old files to transh/ ====;
mkdir trash;
mv pg* trash;
#!/usr/bin/env python
# -*- coding: utf8 -*-
from codecs import encode, decode
print "\n###########################################################\n# #\n# ROT13 is NOT fun! #\n# #\n###########################################################\n"
print "Ctrl+c pour quitter le programme.\n"
def rotatif(source):
source = unicode(source,"utf8")
sortie = encode(source, "rot13")
sortie = "\n"+unicode(decode(sortie, "iso-8859-15"))
return sortie
try:
while 1:
print rotatif(raw_input(u"\nSaisissez une phrase : "))
except KeyboardInterrupt:
print "\n\nTot later!\n"
pass
#TODO if __name__ == __main__ thingie
No preview for this file type
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import nltk
import treetaggerwrapper
texteBrut = u'essai avec un é et/où un à'
tagger = treetaggerwrapper.TreeTagger(TAGLANG='fr',TAGDIR='/usr/share/treetagger',TAGINENC='utf-8',TAGOUTENC='utf-8')
texteTagged = tagger.TagText(texteBrut)
print texteTagged
#!/usr/bin/env python
# -*- coding: utf8 -*-
import getpass, poplib
def monMail(MAILSERVER, USER, PASS):
"""récupération des mails depuis un serveur pop3"""
serveur = poplib.POP3(MAILSERVER)
# serveur.quit()
# print serveur.getwelcome()
serveur.user(USER)
serveur.pass_(PASS)
serveur.list()
(nombreMsg, tailleTotale) = serveur.stat()
if nombreMsg == 0:
print "\n "+USER+" at "+MAILSERVER
return
else:
sortie = ''
print "Récupération de "+`nombreMsg`+" messages pour "+USER+" sur "+MAILSERVER
for nb in range(nombreMsg):
sortie += "Message "+str(nb)+" : \n"
for contenu in serveur.retr(nb+1)[1]:
#print "Header : \n", header
sortie += str(contenu)
serveur.quit()
return sortie
if __name__ == "__main__":
print "\n\nSalut, vieille branche!\n\n"
monMail("pop.free.fr","c33sn0t3b00m","")
#!/usr/bin/env python
#!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Simple IMAP4 client which displays the subjects of all messages in a
particular mailbox.
"""
import sys
from twisted.internet import protocol
from twisted.internet import ssl
from twisted.internet import defer
from twisted.internet import stdio
from twisted.mail import imap4
from twisted.protocols import basic
from twisted.python import util
from twisted.python import log
class TrivialPrompter(basic.LineReceiver):
from os import linesep as delimiter
promptDeferred = None
def prompt(self, msg):
assert self.promptDeferred is None
self.display(msg)
self.promptDeferred = defer.Deferred()
return self.promptDeferred
def display(self, msg):
self.transport.write(msg)
def lineReceived(self, line):
if self.promptDeferred is None:
return
d, self.promptDeferred = self.promptDeferred, None
d.callback(line)
class SimpleIMAP4Client(imap4.IMAP4Client):
"""
A client with callbacks for greeting messages from an IMAP server.
"""
greetDeferred = None
def serverGreeting(self, caps):
self.serverCapabilities = caps
if self.greetDeferred is not None:
d, self.greetDeferred = self.greetDeferred, None
d.callback(self)
class SimpleIMAP4ClientFactory(protocol.ClientFactory):
usedUp = False
protocol = SimpleIMAP4Client
def __init__(self, username, onConn):
self.ctx = ssl.ClientContextFactory()
self.username = username
self.onConn = onConn
def buildProtocol(self, addr):
"""
Initiate the protocol instance. Since we are building a simple IMAP
client, we don't bother checking what capabilities the server has. We
just add all the authenticators twisted.mail has. Note: Gmail no
longer uses any of the methods below, it's been using XOAUTH since
2010.
"""
assert not self.usedUp
self.usedUp = True
p = self.protocol(self.ctx)
p.factory = self
p.greetDeferred = self.onConn
p.registerAuthenticator(imap4.PLAINAuthenticator(self.username))
p.registerAuthenticator(imap4.LOGINAuthenticator(self.username))
p.registerAuthenticator(
imap4.CramMD5ClientAuthenticator(self.username))
return p
def clientConnectionFailed(self, connector, reason):
d, self.onConn = self.onConn, None
d.errback(reason)
def cbServerGreeting(proto, username, password):
"""
Initial callback - invoked after the server sends us its greet message.
"""
# Hook up stdio
tp = TrivialPrompter()
stdio.StandardIO(tp)
# And make it easily accessible
proto.prompt = tp.prompt
proto.display = tp.display
# Try to authenticate securely
return proto.authenticate(password
).addCallback(cbAuthentication, proto
).addErrback(ebAuthentication, proto, username, password
)
def ebConnection(reason):
"""
Fallback error-handler. If anything goes wrong, log it and quit.
"""
log.startLogging(sys.stdout)
log.err(reason)
return reason
def cbAuthentication(result, proto):
"""
Callback after authentication has succeeded.
Lists a bunch of mailboxes.
"""
return proto.list("", "*"
).addCallback(cbMailboxList, proto
)
def ebAuthentication(failure, proto, username, password):
"""
Errback invoked when authentication fails.
If it failed because no SASL mechanisms match, offer the user the choice
of logging in insecurely.
If you are trying to connect to your Gmail account, you will be here!
"""
failure.trap(imap4.NoSupportedAuthentication)
return proto.prompt(
"No secure authentication available. Login insecurely? (y/N) "
).addCallback(cbInsecureLogin, proto, username, password
)
def cbInsecureLogin(result, proto, username, password):
"""
Callback for "insecure-login" prompt.
"""
if result.lower() == "y":
# If they said yes, do it.
return proto.login(username, password
).addCallback(cbAuthentication, proto
)
return defer.fail(Exception("Login failed for security reasons."))
def cbMailboxList(result, proto):
"""
Callback invoked when a list of mailboxes has been retrieved.
"""
result = [e[2] for e in result]
s = '\n'.join(['%d. %s' % (n + 1, m) for (n, m) in zip(range(len(result)), result)])
if not s:
return defer.fail(Exception("No mailboxes exist on server!"))
return proto.prompt(s + "\nWhich mailbox? [1] "
).addCallback(cbPickMailbox, proto, result
)
def cbPickMailbox(result, proto, mboxes):
"""
When the user selects a mailbox, "examine" it.
"""
mbox = mboxes[int(result or '1') - 1]
return proto.examine(mbox
).addCallback(cbExamineMbox, proto
)
def cbExamineMbox(result, proto):
"""
Callback invoked when examine command completes.
Retrieve the subject header of every message in the mailbox.
"""
return proto.fetchSpecific('1:*',
headerType='HEADER.FIELDS',
headerArgs=['SUBJECT'],
).addCallback(cbFetch, proto
)
def cbFetch(result, proto):
"""
Finally, display headers.
"""
if result:
keys = result.keys()
keys.sort()
for k in keys:
proto.display('%s %s' % (k, result[k][0][2]))
else:
print "Hey, an empty mailbox!"
return proto.logout()
def cbClose(result):
"""
Close the connection when we finish everything.
"""
from twisted.internet import reactor
reactor.stop()
def main():
hostname = raw_input('IMAP4 Server Hostname: ')
port = raw_input('IMAP4 Server Port (the default is 143, 993 uses SSL): ')
username = raw_input('IMAP4 Username: ')
password = util.getPassword('IMAP4 Password: ')
onConn = defer.Deferred(
).addCallback(cbServerGreeting, username, password
).addErrback(ebConnection
).addBoth(cbClose)
factory = SimpleIMAP4ClientFactory(username, onConn)
from twisted.internet import reactor
if port == '993':
reactor.connectSSL(hostname, int(port), factory, ssl.ClientContextFactory())
else:
if not port:
port = 143
reactor.connectTCP(hostname, int(port), factory)
reactor.run()
if __name__ == '__main__':
main()
#!/usr/bin/env python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import getpass, poplib
M = poplib.POP3('pop3.free.fr')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
for j in M.retr(i+1)[1]:
print j
M.quit()