繁体   English   中英

python:替换字符串中的特殊字符

[英]python: Replacing special characters in a string

我从MP3标签中读取了歌曲的艺术家,然后根据该名称创建一个文件夹。 我的问题是名称中包含特殊字符(如“ AC \\ DC”)时。 所以我写了这段代码来解决这个问题。

def replace_all(text):
  print "replace_all"
  dictionary = {'\\':"", '?':"", '/':"", '...':"", ':':"", chr(148):"o"}

  for i, j in dictionary.iteritems():
      text = text.replace(i,j)

  return text

我现在遇到的是如何处理非英语字符,例如Motorhead或Blue Oyster崇拜中的umlaout o。

如您所见,我尝试在字典末尾添加umlaout o的ascii字符串版本,但是失败了

UnicodeDecodeError:  'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)

我找到了这段代码,尽管我不理解。

def strip_accents(s):
  return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))

它使我能够从建议的目录/文件名的路径中删除重音符号。

我建议对输入文本和替换的字符都使用unicode。 在您的示例中, chr(148)显然不是Unicode符号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM