2011-06-14 54 views
1

我有下面包含的当前脚本进入扩展名为.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('') 

我从网上的例子粘贴在一起的脚本,所以我不知道这一切的内部运作,因此,如果任何人有做这个脚本是做的更优雅/有效的方式,我愿意改变它。

+1

您想要将当前目录中的所有'* .las'文件重命名为'animals.las'?你打算结束与同名多个文件?这应该如何工作? – 2011-06-14 18:02:25

+0

正确。这将是一个工作目录,我在一个.las文件中拖动,运行脚本,然后将字符串和文件名更正.las文件放回另一个目录。所以多文件问题不是问题。 – 2011-06-14 18:22:06

回答

2

如果您想要以包含* .las内容的名为animals.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() 
+0

'.las'文件中的替换字已经在使用。我无法将'* .las'重命名为'animals.las'。在脚本运行之前,'animals.las'不存在,只有一个随机的'* .las'文件。正如我上面提到的,我知道这会将目录中的任何'.las'重命名为'animals.las'。这对我来说完全没问题。 – 2011-06-14 18:30:31

+0

好的,我的道歉,cnauroth。你实际上是通过创建一个新文件来处理这个问题(我对所有这些都是新的,所以我不理解那个部分)。我把我的代码放入你的更正中,除了将两次原始的'* .las'文件写入'animals.las'文件外,它的工作原理。关于如何修复它的任何想法? 哦!它遍历新创建的'animals.las',因此该文件被写入两次。不过,我会如何得到这个迭代一次? – 2011-06-14 21:13:20