且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

制作有效的文件名......

更新时间:2023-11-29 13:24:58

我建​​议像string.maketrans
http://docs.python.org/lib/node41.html 。我不记得

它是如何工作的,但我认为它类似于

>> invalid_chars =" abc"
replace_chars =" 123"
char_map = string.maketrans(invalid_chars,replace_chars)
filename = " abc123.txt"
filename.translate(charmap)



''123123.txt''


-

Jerry




SpreadTooThin写道:

你好我正在编写一个python脚本,用户创建目录

输入。

有时候用户输入的字符不是

文件或目录名称的有效字符。

以下是我认为有效字符的字符...


有效=

'':。/ ,^ 01 23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL MNOPQRSTUVWXYZ''


如果我有一个名为fname的字符串我想要浏览

中的每个字符文件名,如果它不是有效字符,然后我想用空格替换




这就是我所拥有的:


def fixfilename (fname):

有效=

'':。\,^ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGH IJKLMNOPQRSTUVWXYZ''

for i in range(len(fname) )):

if valid.find(fname [i])< 0:

fname [i] =''''

返回fname


有人想到更简单的解决方案吗?



如果你想剥离''em:


>> valid ='':。/ ,^ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL MNOPQRSTUVWXYZ''
filename =''!"£!£


" ;

Hi I''m writing a python script that creates directories from user
input.
Sometimes the user inputs characters that aren''t valid characters for a
file or directory name.
Here are the characters that I consider to be valid characters...

valid =
'':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL MNOPQRSTUVWXYZ ''

if I have a string called fname I want to go through each character in
the filename and if it is not a valid character, then I want to replace
it with a space.

This is what I have:

def fixfilename(fname):
valid =
'':.\,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGH IJKLMNOPQRSTUVWXYZ ''
for i in range(len(fname)):
if valid.find(fname[i]) < 0:
fname[i] = '' ''
return fname

Anyone think of a simpler solution?

I would suggest something like string.maketrans
http://docs.python.org/lib/node41.html. I don''t remember exactly how
it works, but I think it''s something like
>>invalid_chars = "abc"
replace_chars = "123"
char_map = string.maketrans(invalid_chars, replace_chars)
filename = "abc123.txt"
filename.translate(charmap)

''123123.txt''

--
Jerry



SpreadTooThin wrote:
Hi I''m writing a python script that creates directories from user
input.
Sometimes the user inputs characters that aren''t valid characters for a
file or directory name.
Here are the characters that I consider to be valid characters...

valid =
'':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL MNOPQRSTUVWXYZ ''

if I have a string called fname I want to go through each character in
the filename and if it is not a valid character, then I want to replace
it with a space.

This is what I have:

def fixfilename(fname):
valid =
'':.\,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGH IJKLMNOPQRSTUVWXYZ ''
for i in range(len(fname)):
if valid.find(fname[i]) < 0:
fname[i] = '' ''
return fname

Anyone think of a simpler solution?

If you want to strip ''em:

>>valid='':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL MNOPQRSTUVWXYZ ''
filename = ''!"£!£


"