translate()在python错误中仅接受一个参数(给定2个) [英] translate() takes exactly one argument (2 given) in python error

查看:66
本文介绍了translate()在python错误中仅接受一个参数(给定2个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import os
import re

def rename_files():
    # get the files from dir
    file_list=os.listdir(r"C:\OOP\prank")
    print(file_list)
    saved_path=os.getcwd()
    print("current working directory"+saved_path)
    os.chdir(r"C:\OOP\prank")
    #rename the files
    for file_name in file_list:
        print("old name-"+file_name)
        #print("new name-"+file_name.strip("0123456789"))
        os.rename(file_name,file_name.translate(None,"0123456789"))
        os.chdir(saved_path)

rename_files()

这里由于翻译行而显示错误...帮助我下一步..我正在使用笔译从文件名中删除数字.

Here error is showing due to translate line ...help me what to do next ..I am using translate to remove the digit from filename.

Traceback (most recent call last):
    File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 17, in <module>
rename_files()
      File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 15, in rename_files
     os.rename(file_name,file_name.translate(None,"0123456789"))
     TypeError: translate() takes exactly one argument (2 given)

推荐答案

str.translate需要一个dict,它可以将unicode序号映射到其他unicode序号(如果要删除字符,则为None).您可以这样创建它:

str.translate requires a dict that maps unicode ordinals to other unicode oridinals (or None if you want to remove the character). You can create it like so:

old_string = "file52.txt"
to_remove = "0123456789"
table = {ord(char): None for char in to_remove}
new_string = old_string.translate(table)
assert new_string == "file.txt"

但是,通过使用str.maketrans函数,可以使用一种更简单的方法来创建表.它可以采用各种参数,但是您需要三个arg形式.我们忽略前两个参数,因为它们是用于将字符映射到其他字符的.第三个arg是您要删除的字符.

However, there is simpler way of making a table though, by using the str.maketrans function. It can take a variety of arguments, but you want the three arg form. We ignore the first two args as they are for mapping characters to other characters. The third arg is characters you wish to remove.

old_string = "file52.txt"
to_remove = "0123456789"
table = str.maketrans("", "", to_remove)
new_string = old_string.translate(table)
assert new_string == "file.txt"

这篇关于translate()在python错误中仅接受一个参数(给定2个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆