【发布时间】:2011-06-14 17:57:11
【问题描述】:
我有下面包含的当前脚本,该脚本进入扩展名为 .las 的文件并用其他字符串替换某些字符串(即:猫 -> 小猫,狗 -> 小狗)。
我想要的只是在这个脚本中添加一个功能,当我运行脚本时,它会将任何 .las 文件重命名为当前目录中的某个名称(即:*.las -> animals.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?您是否打算最终得到多个具有相同名称的文件?这应该如何工作? -
正确。这将是一个工作目录,我在其中拖入一个 .las 文件,运行脚本,然后将字符串和文件名更正后的 .las 文件放回另一个目录。所以多文件问题不是问题。