Python:将打印引号、破折号等替换为对应的 ascii 字符

标签 python string

在我的网站上,人们可以发布新闻,相当多的编辑使用 MS word 和类似工具编写文本,然后复制并粘贴到我网站的编辑器中(简单的文本区域,没有 WYSIWYG 等)。

这些文本通常包含“漂亮”的引号而不是普通的 ascii 引号 (")。它们有时还包含那些较长的破折号,例如 而不是 -

现在我想用对应的 ascii 字符替换所有这些字符。但是,我不想删除变音符号和其他非 ascii 字符。我也非常喜欢使用不涉及为所有这些字符创建映射字典的适当解决方案。

我所有的字符串都是 unicode 对象。

最佳答案

这个呢? 它首先创建翻译表,但老实说,我认为没有它你做不到。

transl_table = dict( [ (ord(x), ord(y)) for x,y in zip( u"‘’´“”–-",  u"'''\"\"--") ] ) 

with open( "a.txt", "w", encoding = "utf-8" ) as f_out : 
    a_str = u" ´funny single quotes´ long–-and–-short dashes ‘nice single quotes’ “nice double quotes”   "
    print( " a_str = " + a_str, file = f_out )

    fixed_str = a_str.translate( transl_table )
    print( " fixed_str = " + fixed_str, file = f_out  )

我无法将此打印运行到控制台(在 Windows 上),所以我不得不写入 txt 文件。
a.txt 文件中的输出如下所示:

a_str = ´funny single quotes´ long–-and–-short dashes ‘nice single quotes’ “nice double quotes” fixed_str = 'funny single quotes' long--and--short dashes 'nice single quotes' "nice double quotes"

顺便说一下,上面的代码适用于 Python 3。如果您需要它用于 Python 2,由于两种语言版本处理 Unicode 字符串的差异,它可能需要一些修复

关于Python:将打印引号、破折号等替换为对应的 ascii 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10294032/

相关文章:

ios - 删除字符串开头的非字母字符

python - 在线运行python脚本(django)

python - "IOError: decoder zip not available": Ubuntu Python PIL

python - Python中的字符串查找示例

java - 无法将字符串替换为另一个( boolean 值)-Java

R:如何使用函数参数作为变量名的一部分

java - boolean 逻辑字符串迭代

python - 如何对 python 图像(使用 numpy、opencv 或 PIL)的每个 PIXEL(不是每个 rgb 组件!)应用操作?

python - 在同一个循环中迭代两个列表

python - "Least Astonishment"和可变默认参数