从Unicode字符串中删除文件名中的禁止字符的最有效方法

时间:2014-12-25 12:23:48

标签: python string python-2.7 unicode

我有一个字符串,其中包含我从Web解析的一些数据,并创建一个以此数据命名的文件。

string = urllib.urlopen("http://example.com").read()
f = open(path + "/" + string + ".txt")
f.write("abcdefg")
f.close()

问题在于可能包含以下字符之一:\ / * ? : " < > |。 我正在使用Windows,禁止在文件名中使用这些字符。 此外,string在Unicode formar中,这使得大多数解决方案都无用。

所以,我的问题是:剥离这些角色的最有效/ pythonic方式是什么? 提前谢谢!

编辑:文件名为Unicode格式 str!

2 个答案:

答案 0 :(得分:5)

我们不知道您的数据如何:

但您可以使用re.sub

import re
your_string = re.sub(r'[\\/*?:"<>|]',"","your_string")

答案 1 :(得分:5)

最快的方法是使用unicode.translate

请参阅unicode.translate

In [31]: _unistr = u'sdfjkh,/.,we/.,132?.?.23490/,/' # any random string.

In [48]: remove_punctuation_map = dict((ord(char), None) for char in '\/*?:"<>|')

In [49]: _unistr.translate(remove_punctuation_map)Out[49]: 

u'sdfjkh,.,we.,132..23490,'

删除所有标点符号。

In [46]: remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

In [47]: _unistr.translate(remove_punctuation_map)
Out[47]: u'sdfjkhwe13223490'