背景:我的一个朋友,他可能会有一些强迫症的问题,告诉我一个故事,他如何不打算将他的工作时间用于重命名大量歌曲文件那里有An,The,Of和更多的大写字母。文件重命名;我可以得到一些反馈意见
准则:他给了我一个单词列表,在这里省略,因为你会在代码中看到它们,并告诉我大写字母是O.K.如果他们在歌曲的开头,但是否则他们必须是小写字母。
问题1:这实际上是我的第一个脚本,我正在寻找一些反馈。如果有更好的方法来写这个,我想看看它,所以我可以改进我的编码。该脚本是功能性的,并且正是我想要的。
问题2:最初我没有全部3个功能。我只有取代单词的功能。由于某些原因,它不适用于看起来像这个“月球黑暗面”的文件。当我运行代码时,“Of”将被替换,但“The”将不会被替换。因此,通过试验和错误,我发现如果我小写了文件的第一个字母,那么执行我的替换功能,最后输入大写的文件,它会起作用。任何线索为什么?
import os
words = ['A','An','The','Of','For','To','By','Or','Is','In','Out','If','Oh','And','On','At']
fileList = []
rootdir = ''
#Where are the files? Is the input a valid directory?
while True:
rootdir = raw_input('Where is your itunes library? ')
if os.path.isdir(rootdir): break
print('That is not a valid directory. Try again.')
#Get a list of all the files in the directory/sub-directory's
for root, subFolders, files in os.walk(rootdir):
for file in files:
fileList.append(os.path.join(root))
#Create a function that replaces words.
def rename(a,b,c):
for file in os.listdir(c):
if file.find(a):
os.rename(file,file.replace(a,b))
#Create a function that changes the first letter in a filename to lowercase.
def renameL():
for file in os.listdir(os.getcwd()):
if file.find(' '):
os.rename(file,file.replace(file,file[0].lower()+file[1:]))
#Creat a function that changes the first letter in a filename to uppercase.
def renameU():
for file in os.listdir(os.getcwd()):
if file.find(' '):
os.rename(file,file.replace(file,file[0].upper()+file[1:]))
#Change directory/lowercase the first letter of the filename/replace the offending word/uppercase the first letter of the filename.
for x in fileList:
for y in words:
os.chdir(x)
renameL()
rename(y,y.lower(),x)
renameU()
Exit = raw_input('Press enter to exit.')
欢迎来到SO。一些笔记。这是精确回答精确问题的地方。所以,背景是不需要的。另外,*请提供反馈/意见*类型的问题更适合http://programmers.stackexchange.com。 – 2011-03-09 07:45:55
感谢您的意见。 – Chris 2011-03-09 08:33:23