【发布时间】:2009-07-22 23:57:26
【问题描述】:
我使用的是 python 2.4,但遇到了 unicode 正则表达式的一些问题。我试图为我的问题整理一个非常清晰简洁的例子。看起来 Python 如何识别不同的字符编码存在一些问题,或者我的理解存在问题。非常感谢您观看!
#!/usr/bin/python
#
# This is a simple python program designed to show my problems with regular expressions and character encoding in python
# Written by Brian J. Stinar
# Thanks for the help!
import urllib # To get files off the Internet
import chardet # To identify charactor encodings
import re # Python Regular Expressions
#import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using
rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read()
print (chardet.detect(rawdata))
#print (rawdata)
ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text
UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8
print(chardet.detect(UTF_8_encoded)) # Looks good
# This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML
# Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it
re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE)
print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8")
print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data")
re_amsterdam = re.compile(".*Adobe.*", re.UNICODE)
print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!?
print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8")
'''
# In additon, I tried this regular expression library much to the same unsatisfactory result
new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data")
'''
我正在处理一个替代项目,并且在处理非 ASCII 编码文件时遇到了困难。这个问题是一个更大项目的一部分 - 最终我想用其他文本替换文本(我得到这个在 ASCII 中工作,但我无法识别其他编码中的出现。)再次感谢。
http://brian-stinar.blogspot.com
-布莱恩·J·斯蒂纳尔-
【问题讨论】:
-
您的描述中完全缺少的东西是您的代码失败的方式。你在你的代码中写了“#这完全行不通”,但是你没有暗示它是如何行不通的。打印的字符串是空的吗?您是否收到错误消息/堆栈跟踪?
标签: python regex character-encoding