我需要编写一个脚本,该脚本将浏览文件夹并从图像的字符串中去除文本。
image-w-inch-bob-bob-bob-bob-8820-AV1.jpg
image-w-inch-bob-bob-bob-bob-8820-AV2.jpg
image-w-inch-bob-bob-bob-bob-8820-AV3.jpg
image-w-inch-bob-bob-bob-bob-8820-AV4.jpg
image-w-inch-bob-bob-bob-bob-8820-AV5.jpg
image-w-inch-bob-bob-bob-bob-8820-AV6.jpg
我需要将此重命名为
8820-AV1.jpg
8820-AV2.jpg
8820-AV3.jpg
8820-AV4.jpg
8820-AV5.jpg
8820-AV6.jpg
有人知道这样的脚本吗?
答案 0 :(得分:1)
最自然的方法是使用正则表达式。
这是python实现的示例:
import re
s = 'image-w-inch-bob-bob-bob-bob-8820-AV1.jpg'
capture_from_first_digit_re = re.compile('\D*(\d.*)')
print(capture_from_first_digit_re .findall(s)[0])
您可以根据自己的情况使用它。
简短说明:
将它们放在一起:捕获找到的第一个位数字之后的所有内容。
答案 1 :(得分:0)
如果您的发行版提供了此命令,则很可能可以使用rename来执行此操作。例如:
$ rename 'image-w-inch-bob-bob-bob-bob-' '' image-w-"
或使用PCRE Regex作为表达式:
$ rename 's/image-w-inch-bob-bob-bob-bob-//' image-w-*
重命名可以根据模式匹配(包括通过正则表达式)对一组文件进行批量重命名。请注意,重命名有几种版本,它们接受不同的语法,您应该查阅本地手册和/或命令的帮助页面,以确定要使用的版本以及要使用的确切语法。
答案 2 :(得分:0)
如果您只是想在文件名中找到第一个数字之前剥离所有文本,则在这些行中使用相对简单的正则表达式的方法应该在python中起作用:
import os
import re
# replace with the path to your file:
path = 'test/'
for filename in os.listdir(path):
os.rename(os.path.join(path, filename),
os.path.join(path, re.search('\d.*',filename).group()))
我们可以创建一个测试文件,以使其有趣:
import os
import re
# list out all the filenames to put into our test directory
l=['image-w-inch-bob-bob-bob-bob-8820-AV1.jpg',
'image-w-inch-bob-bob-bob-bob-8820-AV2.jpg',
'image-w-inch-bob-bob-bob-bob-8820-AV3.jpg',
'image-w-inch-bob-bob-bob-bob-8820-AV4.jpg',
'image-w-inch-bob-bob-bob-bob-8820-AV5.jpg',
'image-w-inch-bob-bob-bob-bob-8820-AV6.jpg']
# Create Directory
os.mkdir('test')
# add in all the files
for f in l:
open(f'test/{f}','a').close()
# All the files are there
>>> os.listdir('test')
['image-w-inch-bob-bob-bob-bob-8820-AV5.jpg', 'image-w-inch-bob-bob-bob-bob-8820-AV4.jpg', 'image-w-inch-bob-bob-bob-bob-8820-AV6.jpg', 'image-w-inch-bob-bob-bob-bob-8820-AV3.jpg', 'image-w-inch-bob-bob-bob-bob-8820-AV2.jpg', 'image-w-inch-bob-bob-bob-bob-8820-AV1.jpg']
# rename with the loop provided above:
path = 'test/'
for filename in os.listdir(path):
os.rename(os.path.join(path, filename),
os.path.join(path, re.search('\d.*',filename).group()))
# all the filenames have changed
>>> os.listdir('test')
['8820-AV1.jpg', '8820-AV3.jpg', '8820-AV2.jpg', '8820-AV6.jpg', '8820-AV5.jpg', '8820-AV4.jpg']
答案 3 :(得分:0)
最简单的方法是在文件所在的文件夹中找到python脚本。假设所有文件名的第一个数字前都包含相同数量的字符,那么您将需要:
import os
for file in os.listdir('.'):
if '.py' not in file: #not the python script
os.rename(file, file[indexOfFirstNum:])
我还没有测试脚本,因此请先尝试一下,然后在实际文件夹中运行该脚本之前进行相应的修改。
编辑:如果希望脚本更通用,请参考shlomif的答案。正则表达式对于查找和匹配字符串中的模式很有用。
答案 4 :(得分:0)
这是Perl一种衬板解决方案:
def Contact(request, email):
if request.method == "GET":
form = ContactForm(initial={'contact_email': email)})