我将下面包含的当前脚本放入带有扩展名.las的文件中,并用其他字符串替换某些字符串(即:cat - > kitten,dog - > puppy)。
我想要的只是在这个脚本中添加一个功能,当我运行脚本时,它会将ANY .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('')
我将脚本从在线示例中粘贴在一起,所以我不知道它的所有内部工作原理,所以如果有人有更优雅/更有效的方式来做这个脚本正在做的事情,我愿意改变它。< / p>
答案 0 :(得分:2)
如果你想得到一个名为animals.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()