我有下面包含的当前脚本进入扩展名为.las的文件,并用某些字符串替换某些字符串(例如:cat - > kitten,dog - > puppy)。如何更改此脚本以包含重命名功能?
我只想在这个脚本中添加一个功能,当我运行脚本(即:* .las - > animals.las)时,将ANY .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('')
我从网上的例子粘贴在一起的脚本,所以我不知道这一切的内部运作,因此,如果任何人有做这个脚本是做的更优雅/有效的方式,我愿意改变它。
您想要将当前目录中的所有'* .las'文件重命名为'animals.las'?你打算结束与同名多个文件?这应该如何工作? – 2011-06-14 18:02:25
正确。这将是一个工作目录,我在一个.las文件中拖动,运行脚本,然后将字符串和文件名更正.las文件放回另一个目录。所以多文件问题不是问题。 – 2011-06-14 18:22:06