如何解释Python 3.6中的str.maketrans函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41535571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to explain the str.maketrans function in Python 3.6?
提问by Dennis
I am currently participating in an Udacity course that instructs students on programming using Python. One of the projects has students rename photo files (remove any numbers in the name) in a directory in order to have the files arranged alphabetically, after which a secret message will be spelled out. For instance, if a file name is "48athens"
, the program seeks to remove the numbers, leaving only "athens"
as the file name.
我目前正在参加 Udacity 课程,该课程指导学生使用 Python 进行编程。其中一个项目让学生重命名目录中的照片文件(删除名称中的任何数字),以便按字母顺序排列文件,然后将拼出一条秘密信息。例如,如果文件名是"48athens"
,程序会试图删除数字,只留下"athens"
文件名。
I am using Python 3.6, while the course instructor is using Python 2.7. I should likely be using Python 2.7 so as to simplify the learning process. However, for now I will keep using Python 3.6.
我使用的是 Python 3.6,而课程讲师使用的是 Python 2.7。我应该使用 Python 2.7 来简化学习过程。但是,现在我将继续使用 Python 3.6。
The way in which the instructor has the files renamed is using the .translate
function, which takes two arguments in Python 2.x, while Python 3.x only takes one argument. It removes any numbers (0 through 9) from the file names.
教师重命名文件的方式是使用.translate
函数,它在 Python 2.x 中接受两个参数,而在 Python 3.x 中只接受一个参数。它从文件名中删除任何数字(0 到 9)。
import os
def rename_files(): #Obtain the file names from a folder.
file_list = os.listdir(r"C:\Users\Dennis\Desktop\OOP\prank\prank")
print (file_list)
saved_path = os.getcwd()
os.chdir(r"C:\Users\Dennis\Desktop\OOP\prank\prank")
for file_name in file_list: #Rename the files inside of the folder.
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()
However, this does not work in Python 3.x, as it says that:
但是,这在 Python 3.x 中不起作用,因为它说:
TypeError: translate() takes exactly one argument (2 given)
Thankfully, I found another way using someone's assistance. However, I'm not really sure how it works. Can someone explain the str.maketrans
function to me, and what the first two blank arguments in quotes are for? My thought is that it's saying: for the first two characters in the file name, remove any numbers (0 through 9). Is that correct? For instance, in "48athens"
, remove the first two characters (4 and 8) if they are numbers between 0 and 9.
谢天谢地,我找到了另一种使用他人帮助的方法。但是,我不确定它是如何工作的。有人可以str.maketrans
向我解释这个函数,引号中的前两个空白参数是做什么用的?我的想法是它的意思是:对于文件名中的前两个字符,删除任何数字(0 到 9)。那是对的吗?例如,在 中"48athens"
,如果前两个字符(4 和 8)是 0 到 9 之间的数字,则删除它们。
import os
def rename_files(): #Obtain the file names from a folder.
file_list = os.listdir(r"C:\Users\Dennis\Desktop\OOP\prank\prank")
print (file_list)
saved_path = os.getcwd()
os.chdir(r"C:\Users\Dennis\Desktop\OOP\prank\prank")
for file_name in file_list: #Rename the files inside of the folder.
os.rename(file_name, file_name.translate(str.maketrans('','','0123456789')))
os.chdir(saved_path)
rename_files()
My Understanding of the Documentation:
我对文档的理解:
static str.maketrans(x[, y[, z]])
This static method returns a translation table usable forstr.translate()
.
static str.maketrans(x[, y[, z]])
此静态方法返回可用于 的转换表str.translate()
。
It's saying that the arguments passed to str.maketrans
, along with the actual function str.maketrans
, will make a table that says, "If this character appears, replace it with this character." However, I'm not sure what the brackets are for.
它是说传递给 的参数str.maketrans
以及实际的函数str.maketrans
将生成一个表格,上面写着“如果出现此字符,请用此字符替换它”。但是,我不确定括号的用途。
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.
如果只有一个参数,它必须是将 Unicode 序数(整数)或字符(长度为 1 的字符串)映射到 Unicode 序数、字符串(任意长度)或 None 的字典。然后字符键将被转换为序数。
It's saying that it can only change integers, or characters in strings of length one, to other integers or strings (of any length you want). But I believe I have three arguments, not one.
它是说它只能将整数或长度为 1 的字符串中的字符更改为其他整数或字符串(您想要的任何长度)。但我相信我有三个论点,而不是一个。
If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
如果有两个参数,它们必须是等长的字符串,并且在生成的字典中,x 中的每个字符都会映射到 y 中相同位置的字符。如果有第三个参数,它必须是一个字符串,其字符将在结果中映射为 None 。
I have three arguments ('', '', '0123456789')
. I think x
is the first ''
, and y
is the second ''
. I have the third argument, which is a string '0123456789'
, but I don't understand what it means to be mapped to 'None'
.
我有三个论点('', '', '0123456789')
。我认为x
是第一个''
,而且y
是第二个''
。我有第三个参数,它是一个 string '0123456789'
,但我不明白映射到'None'
.
回答by Patrick Haugh
str.maketrans
builds a translation table, which is a mapping of integers or characters to integers, strings, or None
. Think of it like a dictionary. We go through the string to translate and replace everything that appears as a key in the mapping with whatever its value in the map is.
str.maketrans
构建一个转换表,它是整数或字符到整数、字符串或 的映射None
。把它想象成一本字典。我们遍历字符串来翻译和替换在映射中作为键出现的所有内容,无论它在映射中是什么值。
You can build a translation table with one, two, three arguments (I think this may be what's confusing you). With one argument:
您可以使用一个、两个、三个参数构建一个转换表(我认为这可能会让您感到困惑)。有一个论点:
str.maketrans({'a': 'b', 'c': None})
You give the function a mapping that follows the rules for translation tables and it returns an equivalent table for that mapping. Things that map to None
are removed
您为函数提供了一个遵循转换表规则的映射,它返回该映射的等效表。映射到的东西None
被移除
With two arguments:
有两个论点:
str.maketrans('abc', 'xyz')
You give it two strings. Each character in the first string is replaced by the character at that index in the second string. So 'a'
maps to 'x'
, 'b'
to 'y'
, and 'c'
to 'z'
.
你给它两个字符串。第一个字符串中的每个字符都被第二个字符串中该索引处的字符替换。所以'a'
映射到'x'
、'b'
到'y'
和'c'
到'z'
。
The one you're using, with three arguments, works the same as two arguments, but has a third string.
您正在使用的带有三个参数的参数与两个参数的工作方式相同,但具有第三个字符串。
str.maketrans('abc', 'xyz', 'hij')
This is the same as the two argument version, except that the characters from the third string are removed, as if they were mapped to None
. So your table is saying "Don't replace anything, but remove the characters that show up in this string".
这与两个参数版本相同,只是删除了第三个字符串中的字符,就好像它们被映射到None
. 所以你的表说“不要替换任何东西,但删除出现在这个字符串中的字符”。
回答by Dimitris Fasarakis Hilliard
From the documentation on str.maketrans
:
If there is a third argument, it must be a string, whose characters will be mapped to
None
in the result.
如果有第三个参数,它必须是一个字符串,其字符将被映射到
None
结果中。
This is what str.maketrans
is doing; it is taking each element in the third argument and creating a map (a Python dictionary) that maps each ordinal value of the characters in the string to None
:
这就是str.maketrans
正在做的事情;它采用第三个参数中的每个元素并创建一个映射(Python 字典),将字符串中字符的每个序数值映射到None
:
>>> str.maketrans('', '', '0123456789')
{48: None,
49: None,
50: None,
51: None,
52: None,
53: None,
54: None,
55: None,
56: None,
57: None}
If extra values exist as the first and second arguments, they are added to this mapping as additional characters to be translated(this is why the author selected ''
and ''
; he doesn't want extra characters to be translated):
如果第一个和第二个参数存在额外的值,它们将作为要翻译的额外字符添加到此映射中(这就是作者选择''
and 的原因''
;他不想翻译额外的字符):
>>> str.maketrans('a', 'A', '0123456789')
{48: None,
49: None,
50: None,
51: None,
52: None,
53: None,
54: None,
55: None,
56: None,
57: None,
97: 65} # map ord('a') to ord('A')
If you apply this to your string now, it'll also capitalize 'athens'
to 'Athens'
due to the extra 'a', 'A'
we've provided to maketrans
. Not the finest of translations but suffices to grasp the functionality.
如果你申请了此信息字符串现在,它还会利用'athens'
到'Athens'
,由于额外的'a', 'A'
我们提供的maketrans
。不是最好的翻译,但足以掌握功能。
str_obj.translate
will then perform look-ups on this dictionary for every character in str_obj
replacing its values with the ones found in the mapping. If it doesn't find it inside the mapping, it leaves it as-is, if it is None
it removes it. This is stated in the documentation for str.translate
:
str_obj.translate
然后将在这个字典上查找每个字符,str_obj
用映射中找到的值替换它的值。如果它在映射中没有找到它,它会保持原样,如果是,None
它会删除它。这在文档中说明str.translate
:
When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return
None
, to delete the character from the return string; or raise aLookupError
exception, to map the character to itself.
当由 Unicode 序数(整数)索引时,表对象可以执行以下任一操作: 返回 Unicode 序数或字符串,将字符映射到一个或多个其他字符;return
None
,从返回字符串中删除字符;或引发LookupError
异常,将字符映射到自身。
(Emphasis mine)
(强调我的)
回答by Akash
import string
import os
# Required to call maketrans function.
#trantab = maketrans()
def rename_files():
x=os.listdir(r'C:\Users\user\Desktop\prank')
print (x)
path=os.getcwd()
print("path is"+path)
os.chdir(r'C:\Users\user\Desktop\prank')
for file in x:
os.rename(file,file.translate(file.maketrans('','','0123456789')))
rename_files()
回答by mhmdy
You could simply use:
你可以简单地使用:
str.replace('num', '')
this will replace num
for any num in '1234567890'
with empty strings, that's removing it.
这将用空字符串替换num
任何 num '1234567890'
,即删除它。