Python 2.7 dict删除智能引号

Python 2.7 dict删除智能引号,python-2.7,text,unicode,Python 2.7,Text,Unicode,我想写一个类似的脚本来替换这里回答的文本中的智能引号和卷曲撇号:有人能解释一下这两行吗: charmap = [ (u"\u201c\u201d", "\""), (u"\u2018\u2019", "'") ] _map = dict((c, r) for chars, r in charmap for c in list(chars)) fixed = "".join(_map.get(c, c) for c in s) print fixed 可能会用更冗长的格式重写它们,

我想写一个类似的脚本来替换这里回答的文本中的智能引号和卷曲撇号:有人能解释一下这两行吗:

charmap = [
  (u"\u201c\u201d", "\""),
  (u"\u2018\u2019", "'")
  ]

_map = dict((c, r) for chars, r in charmap for c in list(chars))
fixed = "".join(_map.get(c, c) for c in s)
print fixed
可能会用更冗长的格式重写它们,并添加注释来解释到底发生了什么-我有点搞不清楚这是一个内部/外部循环组合还是对字典中的项目进行顺序检查

_map = dict((c, r) for chars, r in charmap for c in list(chars))
fixed = "".join(_map.get(c, c) for c in s)
指:

_map = dict((c, r) for chars, r in charmap for c in list(chars))

意味着

作为方法,
.join
只是将序列元素与给定字符串作为分隔符连接在一起(在本例中,
,即没有分隔符)

指:

_map = dict((c, r) for chars, r in charmap for c in list(chars))

意味着


作为方法,
.join
简单地将序列元素与给定字符串连接起来,作为它们之间的分隔符(在这种情况下,
“”
,即没有分隔符)

使用内置的字符串函数
translate

fixed = ""                          # an empty string   
for c in s:
    fixed = fixed + _map.get(c, c)  # first "c" is key, second is default for "not found"
输出:

#!python2
#coding: utf8

# Start with a Unicode string.
# Your codecs.open() will read the text in Unicode
text = u'''\
"Don't be dumb"
“You’re smart!”
'''

# Build a translation dictionary.
# Keys are Unicode ordinal numbers.
# Values can be ordinals, Unicode strings, or None (to delete)
charmap = { 0x201c : u'"',
            0x201d : u'"',
            0x2018 : u"'",
            0x2019 : u"'" }

print text.translate(charmap)

使用内置的字符串函数
translate
,速度更快、更直观:

fixed = ""                          # an empty string   
for c in s:
    fixed = fixed + _map.get(c, c)  # first "c" is key, second is default for "not found"
输出:

#!python2
#coding: utf8

# Start with a Unicode string.
# Your codecs.open() will read the text in Unicode
text = u'''\
"Don't be dumb"
“You’re smart!”
'''

# Build a translation dictionary.
# Keys are Unicode ordinal numbers.
# Values can be ordinals, Unicode strings, or None (to delete)
charmap = { 0x201c : u'"',
            0x201d : u'"',
            0x2018 : u"'",
            0x2019 : u"'" }

print text.translate(charmap)

关于这两行,您到底不了解什么?第一行通过生成元组(char=>replacement)创建dict,第二行对每个char应用dict转换,如果不在dict.@jornsharpe中,则默认为原始值。我不确定_-map是否是一个新字典,它同时在charmap中查找项目,还是在一个内部循环中查找以c作为字符列表的项目。第二行比较简单,但我不熟悉。获取(c,c)那么你试着打印地图了吗?阅读dict.get上的文档?@jornsharpe不,这是明智的做法。我对在那个阶段实际可以打印什么感到非常困惑——我认为大多数事情都会在打印过程中出现错误,_map可能是不可打印的unicode或unicode,此时不打印到DOS终端。:)关于这两行,您到底不了解什么?第一行通过生成元组(char=>replacement)创建dict,第二行对每个char应用dict转换,如果不在dict.@jornsharpe中,则默认为原始值。我不确定_-map是否是一个新字典,它同时在charmap中查找项目,还是在一个内部循环中查找以c作为字符列表的项目。第二行比较简单,但我不熟悉。获取(c,c)那么你试着打印地图了吗?阅读dict.get上的文档?@jornsharpe不,这是明智的做法。我对在那个阶段实际可以打印什么感到非常困惑——我认为大多数事情都会在打印过程中出现错误,_map可能是不可打印的unicode或unicode,此时不打印到DOS终端。:)