아래에 포함 된 현재 스크립트는 확장명이 .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('')
나는 온라인 예에서 함께 스크립트를 붙여, 그래서 누군가가이 스크립트가하고있는 일을 더 우아한/효율적인 방법이 있다면, 나는 문을 열어주는 말들 그것을 바꾼다.
: 각 * .las는 가까운 animals.las을 animals.las에 파일을, 그리고? 같은 이름의 여러 파일로 끝내려고하십니까? 이게 어떻게 작동할까요? –
수정하십시오. 이것은 하나의 .las 파일에서 드래그하고 스크립트를 실행 한 다음 문자열과 파일 이름을 수정 한 .las 파일을 다시 다른 디렉토리에 저장하는 작업 디렉토리입니다. 그래서 여러 파일 문제는 문제가되지 않습니다. –