【发布时间】:2017-10-05 19:31:31
【问题描述】:
我有一个功能,旨在使文件名或 URL 的某些文本安全。我正在尝试对其进行更改,以便它在 Python 2 和 Python 3 中工作。在我的尝试中,我将自己与字节码混淆了,并欢迎一些指导。我遇到了像sequence item 1: expected a bytes-like object, str found 这样的错误。
def slugify(
text = None,
filename = True,
URL = False,
return_str = True
):
if sys.version_info >= (3, 0):
# insert magic here
else:
if type(text) is not unicode:
text = unicode(text, "utf-8")
if filename and not URL:
text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore")
text = unicode(re.sub("[^\w\s-]", "", text).strip())
text = unicode(re.sub("[\s]+", "_", text))
elif URL:
text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore")
text = unicode(re.sub("[^\w\s-]", "", text).strip().lower())
text = unicode(re.sub("[-\s]+", "-", text))
if return_str:
text = str(text)
return text
【问题讨论】:
标签: regex string python-3.x unicode bytecode