Path: csiph.com!usenet.pasdenom.info!aioe.org!news.stack.nl!newsfeed.xs4all.nl!newsfeed3.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.002 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'argument': 0.05; 'string': 0.09; 'encode': 0.09; 'imported': 0.09; 'main()': 0.09; 'msg': 0.09; 'pgp': 0.09; 'received:localnet': 0.09; 'try:': 0.09; 'python': 0.11; 'def': 0.12; '161,': 0.16; '57,': 0.16; '__future__': 0.16; 'codec': 0.16; 'filenames,': 0.16; 'help?': 0.16; 'message):': 0.16; 'ordinal': 0.16; 'skip:" 70': 0.16; 'soup': 0.16; 'typeerror:': 0.16; 'vectors': 0.16; 'written': 0.21; 'header:User-Agent:1': 0.23; 'passes': 0.24; 'skip:e 30': 0.24; 'unicode': 0.24; "i've": 0.25; 'script': 0.25; 'skip:" 30': 0.26; 'skip:" 40': 0.26; 'skip:v 30': 0.26; 'train': 0.26; 'pass': 0.26; 'gets': 0.27; 'tried': 0.27; 'feature': 0.29; 'skip:p 30': 0.29; 'character': 0.29; 'matching': 0.30; "i'm": 0.30; 'becoming': 0.31; 'crash': 0.31; 'file': 0.32; 'skip:c 30': 0.32; 'thanks!': 0.32; 'run': 0.32; '(most': 0.33; 'skip:d 20': 0.34; 'subject:with': 0.35; "can't": 0.35; 'except': 0.35; 'skip:s 30': 0.35; 'convert': 0.35; 'received:84': 0.35; 'but': 0.35; 'minutes,': 0.36; 'url:org': 0.36; 'list': 0.37; 'server': 0.38; 'filter': 0.38; 'stable': 0.38; 'skip:[ 10': 0.38; 'to:addr :python-list': 0.38; 'recent': 0.39; 'to:addr:python.org': 0.39; 'skip:p 20': 0.39; 'skip:u 10': 0.60; 'most': 0.60; 'skip:t 30': 0.61; 'matter': 0.61; 'skip:* 10': 0.61; 'here': 0.66; 'reads': 0.68; 'realized': 0.68; 'skip:r 40': 0.68; 'desperate': 0.84; 'florian': 0.84; 'messages:': 0.91 From: Florian Lindner To: python-list@python.org Subject: Trouble with UnicodeEncodeError and email Date: Wed, 08 Jan 2014 14:14:29 +0100 User-Agent: KMail/4.12 (Linux/3.12.6-1-ARCH; KDE/4.12.0; x86_64; ; ) MIME-Version: 1.0 Content-Transfer-Encoding: 7Bit Content-Type: text/plain; charset="utf-8" X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 74 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1389187223 news.xs4all.nl 2925 [2001:888:2000:d::a6]:50951 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:63473 Hello! I've written some tiny script using Python 3 and it used to work perfectly. Then I realized it needs to run on my Debian Stable server too, which offers only Python 2. Ok, most backporting was a matter of minutes, but I'm becoming desperate on some Unicode error... i use scikit-learn to train a filter on a set of email messages: vectorizer = CountVectorizer(input='filename', decode_error='replace', strip_accents='unicode', preprocessor=self.mail_preprocessor, stop_words='english') http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html The vectorizer gets a list of filenames, reads them and passes them to the preprocessor: def mail_preprocessor(self, message): # Filter POPFile cruft by matching date string at the beginning. print("Type:", type(message)) # imported from __future__ pop_reg = re.compile(r"^[0-9]{4}/[0-1][1-9]/[0-3]?[0-9]") message = [line for line in message.splitlines(True) if not pop_reg.match(line)] xxx = "".join(message) msg = email.message_from_string(xxx) # <-- CRASH here msg_body = "" for part in msg.walk(): if part.get_content_type() in ["text/plain", "text/html"]: body = part.get_payload(decode=True) soup = BeautifulSoup(body) msg_body += soup.get_text(" ", strip=True) if "-----BEGIN PGP MESSAGE-----" in msg_body: msg_body = "" msg_body += " ".join(email.utils.parseaddr(msg["From"])) try: msg_body += " " + msg["Subject"] except TypeError: # Can't convert 'NoneType' object to str implicitly pass msg_body = msg_body.lower() return msg_body Type: Traceback (most recent call last): File "flofify.py", line 182, in main() File "flofify.py", line 161, in main model.train() File "flofify.py", line 73, in train vectors = vectorizer.fit_transform(data[:,1]) File "/usr/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 780, in fit_transform vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary) File "/usr/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 715, in _count_vocab for feature in analyze(doc): File "/usr/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 229, in tokenize(preprocess(self.decode(doc))), stop_words) File "flofify.py", line 119, in mail_preprocessor msg = email.message_from_string(xxx) File "/usr/lib/python2.7/email/__init__.py", line 57, in message_from_string return Parser(*args, **kws).parsestr(s) File "/usr/lib/python2.7/email/parser.py", line 82, in parsestr return self.parse(StringIO(text), headersonly=headersonly) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 1624: ordinal not in range(128) I've tried various modifications like encoding/decoding the message argument to utf-8. Any help? Thanks! Florian