Python 如何更改此脚本以同时包含重命名功能?

Python 如何更改此脚本以同时包含重命名功能?,python,wildcard,rename,Python,Wildcard,Rename,我有下面包含的当前脚本,它进入一个扩展名为.las的文件,并用其他字符串替换某些字符串(即:cat->kitten,dog->puppy) 我只想在这个脚本中添加一个功能,当我运行脚本时,它可以将任何.las文件重命名为当前目录中的某个名称(即:*.las->anives.las) 我会将一个文件拖到这个目录中,运行脚本,执行文本替换和重命名,然后将文件移出当前目录。所以对于这个脚本,我不在乎它是否会将多个.las文件重写为一个名称 # read a text file, replace mul

我有下面包含的当前脚本,它进入一个扩展名为.las的文件,并用其他字符串替换某些字符串(即:cat->kitten,dog->puppy)

我只想在这个脚本中添加一个功能,当我运行脚本时,它可以将任何.las文件重命名为当前目录中的某个名称(即:*.las->anives.las)

我会将一个文件拖到这个目录中,运行脚本,执行文本替换和重命名,然后将文件移出当前目录。所以对于这个脚本,我不在乎它是否会将多个.las文件重写为一个名称

# read a text file, replace multiple words specified in a dictionary
# write the modified text back to a file

import re
import os
import time

# the dictionary has target_word:replacement_word pairs
word_dic = {
'cat' : 'kitten',
'dog' : 'puppy'
}


def replace_words(text, word_dic):
    """
    take a text and replace words that match a key in a dictionary with
    the associated value, return the changed text
    """
    rc = re.compile('|'.join(map(re.escape, word_dic)))
    def translate(match):
        return word_dic[match.group(0)]
    return rc.sub(translate, text)

def scanFiles(dir): 
    for root, dirs, files in os.walk(dir):
        for file in files:
            if '.las' in file:
            # read the file
                fin = open(file, "r")
                str2 = fin.read()
                fin.close()
            # call the function and get the changed text
                str3 = replace_words(str2, word_dic)
            # write changed text back out
                fout = open(file, "w")
                fout.write(str3)
                fout.close()
                #time.sleep(1)



scanFiles('')

我将在线示例中的脚本粘贴在一起,因此我不知道它的所有内部工作原理,因此,如果有人有更优雅/高效的方法来执行此脚本的操作,我愿意对其进行更改。

如果您希望最终得到一个名为anives.las的文件,其中包含*.las的内容,然后,您可以将scanFiles功能更改为在循环开始时打开animals.las,将每个*.las文件的翻译输出写入animals.las,然后关闭animals.las:

def scanFiles(dir): 
    fout = open("animals.las", "w")
    for root, dirs, files in os.walk(dir):
        for file in files:
            if '.las' in file:
            # read the file
                fin = open(file, "r")
                str2 = fin.read()
                fin.close()
            # call the function and get the changed text
                str3 = replace_words(str2, word_dic)
            # write changed text back out
                fout.write(str3)
                #time.sleep(1)
    fout.close()

是否要将当前目录中的所有
*.las
文件重命名为
动物.las
?您是否打算以多个同名文件结束?这是怎么回事?没错。这将是一个工作目录,我在其中拖入一个.las文件,运行脚本,然后将字符串和文件名更正后的.las文件放回另一个目录。因此,多文件问题不是问题。
.las
文件中的单词替换已经开始工作。我很难将
*.las
重命名为
动物.las
。在脚本运行之前,
anives.las
不存在,只有随机的
*.las
文件存在。如上所述,我知道这会将目录中的任何
.las
重命名为
animals.las
。这对我来说完全没关系。好吧,我道歉,克纳罗斯。实际上,您通过动态创建一个新文件解决了这个问题(我对这一切都是新手,所以我不理解这一部分)。我将您的更正输入到我的代码中,除了它将原始的
*.las
文件写入
animals.las
文件两次之外,它仍然有效。有没有办法解决这个问题?哦它遍历新创建的
anives.las
,因此文件被写入两次。不过,我怎样才能让这个迭代只进行一次呢?