如何解决如何更改此脚本以包含重命名功能?
| 我有下面包含的当前脚本,该脚本进入扩展名为.las的文件中,并用其他字符串替换某些字符串(即:猫->小猫,狗->小狗)。 我只想在此脚本中添加一个功能,以便在运行脚本时将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(\'\')
我从在线示例中将脚本粘贴在一起,所以我不知道它的所有内部工作原理,因此,如果有人能以更优雅/更有效的方式来执行此脚本,则可以更改它。
解决方法
如果您想结束一个包含* .las内容的名为animals.las的文件,则可以在循环开始时将scanFiles函数更改为打开animals.las,编写每个* .las的翻译输出。归档到animals.las,然后关闭animal.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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。