Python 3.4 - Extracting unicode

Attached code fails to match extended ASCII character (e.g. the cross character x, or the u-umlaud Künkele).
The sample code fetches url = ""
and looks for lines of the form

<i class="genus">Dactylorhiza</i> <i class="specieshybrid">×</i>&nbsp;<i class="species">abantiana</i> <span class="authorship">H.Baumann & Künkele</span>

It then extracts 6 values (bold faced).  The code fails to return strings that contain any extended ASCII characters.  Decoding to utf-8 doesn't help.

How do I fix this?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
That page says it is displaying the content in UT8 already... so it's not surprising that 'Decoding to utf-8 doesn't help.'  The small 'x' is found on this page and it is a two-byte character in UTF8.  Which is not "extended ASCII".
Not exactly sure what you think it's failing to return.  

I think your biggest problem is that your masking your true problem in your try/except block.   The default codepage for an English language Windows console doesn't have the characters you want to display so python throws an exception on your print(x).  That exception will cause it to fall into the except block and skip over the code that writes those lines to your file.

Either move the write to the file up before the print or encode the data that you're planning on printing to the console to something a little safer  (e.g.)

Open in new window

In other words, try this:
	try:	#-- look for source info
		w ='class="genus">([^<]+)</i>.*?(?:class="specieshybrid">([^<]*)</i>){0,1}.*?class="species">([^<]+)</i>.*?(?:class="infraspr">([^<]+)</span>){0,1}.*?(?:class="infraspe">([^<]+)</i>){0,1}.*?class="authorship">([^<]+)</span>',str(gline))
		x = '{0},{1},{2},{3},{4},{5}\n'.format(,,,,,
	except Exception as e:

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
cpeters5Author Commented:
Thank you clockwatcher, I got the extended characters part fixed.  Now, how do I get the cross character "x"?  Result still shows "None" for them.

Dave Baldwin, Thanks for pointing out the utf-8 already declared from the source (however, without the
    gline = gline.decode('utf-8') block, I got \xc3\xbc output for the u-umlaud.)   I don't really understand how to handle non-ASCII characters.
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

Dave BaldwinFixer of ProblemsCommented:
I don't either.  I just know about the problem, not so much what to do about it.
Your problem isn't with non-ascii characters.  It's with your regular expression.


I know what you're trying to do but that regular expression of yours is incredibly tough to read with all the optional stuff you've got going on with it.  And the optional stuff is what is causing your problems, with it in there, you'll notice your group isn't picked up.  With it out, you'll see it is:

import re

line = '<i class="genus">Dactylorhiza</i> <i class="specieshybrid">WHATEVER</i>&nbsp;<i class="species">abantiana</i> <span class="authorship">H.Baumann & Knkele</span>'

m ='class="genus">([^<]+)</i>.*?(?:class="specieshybrid">([^<]*)</i>){0,1}.*?class="species">([^<]+)</i>.*?(?:class="infraspr">([^<]+)</span>){0,1}.*?(?:class="infraspe">([^<]+)</i>){0,1}.*?class="authorship">([^<]+)</span>',line)
print(   # returns None

m ='class="genus">([^<]+)</i>.*?(?:class="specieshybrid">([^<]*)</i>).*?class="species">([^<]+)</i>.*?(?:class="infraspr">([^<]+)</span>){0,1}.*?(?:class="infraspe">([^<]+)</i>){0,1}.*?class="authorship">([^<]+)</span>',line)
print(  # returns WHATEVER

Open in new window

Anyway... it has nothing to do with the non-ascii characters.   As you can see from the above.

I really suggest using a HTML parser/treebuilder (e.g., BeautifulSoup) to parse HTML rather than muck about with regular expressions like you're trying to do.  It's going to make your code much more maintainable.

If you want to stick with just regular expressions, I would suggest breaking things up into manageable chunks and using multiple regular expressions to find what you're after rather than try to get everything done in one.   Something along the lines of:

import re
import urllib.request

url = ""

page = urllib.request.urlopen(url).read().decode('utf-8')
for td_match in re.finditer("<td.*?>(.*?)</td>", page, flags=re.DOTALL):
    td_html =
    if'class="genus"', td_html):
        match ='<i class="genus">(.*?)</i>', td_html)
        if match:
            genus =

        match ='<i class="specieshybrid">(.*?)</i>', td_html)
        if match:
            species_hybrid =

        match ='<span class="authorship">(.*?)</span>', td_html)
        if match:
            authorship =

        print("Genus: {0}\nHybrid: {1}\nAuthor: {2}".format(genus, species_hybrid.encode('unicode-escape'), authorship.encode('unicode-escape')))

Open in new window

The problem is that you probably cannot force the regular expression engine to choose the variant that you prefer. When you look at

Open in new window

the correct match is also to ignore the specieshybrid part and eat it using the following .*?

The more complex the regular expression is, the less control you have.

Anyway, you can at least break them to more readable pieces:
rex = re.compile(r'''class="genus">([^<]+)</i>.*?
                     </span>''', re.VERBOSE)

Open in new window

cpeters5Author Commented:
Sorry guys for the messy code.  THis is my first Python code and I haven't shreded my Perl habit quite yet!
However, I took clockwatcher and pepr suggested and simplify.
Turns out it is really font problem.  When stripped off all other search criteria, just searching for the cross character. I got the error message

t ='(?:"specieshybrid">(.*))</i>',gline)

'charmap' codec can't encode character '\xd7' in position 0: character maps to <undefined>

Open in new window

According to the utf-8 character table, the unicode code point of the cross sign × is U+00D7 (which is interpreted to \xd7?) and is represented in hex by  c3 97.

I suspect it is the matter of how to decode "gline" to get \xd7 detected
Yes, the `\x` escape means that the unicode character is expressed as a number using the next two hexadecimal digits. Similarly, the `\u` says that the next four characters are hexadecimal digits of the character ordinal value.

Your code is fine. The problem is related to the `print` itself. It is not capable to convert the special character for displaying on the console. (Console does not support unicode, and the character cannot be converted to 8-bit encoding.) You can write it to the file instead of printing to console. Then you will see it works.

Use r'raw string' literals for regular expression patterns to avoid doubling backslashes (similar to Perl's /rawstring/ in patterns, if I recall correctly).
cpeters5Author Commented:
Hi pepr,
I did just that. No deal.  Problem with both print and write to file.  
At this point, I will just drop this part of the question.  I need to finish the code soon before my attention goes somewhere else :-)

I am taking a workaround by simply detecting specieshybrid string, and if exist, then just write the "×" to that record.  This works (I am 95% sure the specieshybrid tag is consistent with the existence of the ×)  I still wish to learn how to handle these non ascii characters properly in python.  

Thank you all for your help.
cpeters5Author Commented:
Thank you all for the help.  Thanks also to  clockwatcher, although I didn't try his suggestion to use an HTML parser, being new to Python (I haven't gotten very deep into the tutorial yet.)  This is just a quick and dirty code that I need to finish in a short time.  I will revisit it later and by then I will have more time and skill to do it properly, perhaps with BeautifulSoup.
Try the following:
s = '\xd7'    # the same as '\u00d7'
with open('test.txt', 'w', encoding='utf-8') as f:

Open in new window

The test.txt file should contain two bytes with hexa values c3 97. When observing it with your favourite UTF-8 capable editor, you will see the special 'x'. The next print will fail in your case.
cpeters5Author Commented:
I just post another related question:
cpeters5Author Commented:
Never mind, I got it!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.