我正在尝试编写一个简单的程序,该程序将在给定目录中打开文本文件以搜索与给定模式匹配的所有字符串,并在删除所有其他信息的同时将它们替换为所需的字符串。我有两个.txt文件:
User_321.txt,其中包含:
321_AliceKelly001.jpg [size_info] [date_info] [geo_location_info] ... [other info]
321_AliceKelly002.jpg [size_info] [date_info] [geo_location_info] ... [other info]
321_AliceKelly003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
...
321_AliceKelly125.jpg [size_info] [date_info] [geo_location_info] ... [other info]
和User_205.txt,其中包含:
205_CarlCarlson001.jpg [size_info] [date_info] [geo_location_info] ... [other info]
205_CarlCarlson002.jpg [size_info] [date_info] [geo_location_info] ... [other info]
205_CarlCarlson_003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
205_CarlCarlson007.jpg [size_info] [date_info] [geo_location_info] ... [other info]
我希望User_321.txt包含:
321_AliceKelly_001.jpg
321_AliceKelly_002.jpg
321_AliceKelly_003.jpg
...
321_AliceKelly_125.jpg
和User_205.txt包含:
205_CarlCarlson_001.jpg
205_CarlCarlson_002.jpg
205_CarlCarlson_003.jpg
205_CarlCarlson_007.jpg
所以我只想在名称和最后3位数字之间添加“ _”。我能够处理所有条目都是统一的情况,即仅包含以下形式的条目:
\d\d\d_[a-zA-Z]\d\d\d.jpg [size_info] [date_info] [geo_location_info] ... [other info]
使用以下代码:
import os, re,
path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]
desired_text = re.compile(r'\w+.jpg')
#desired_ending = re.compile(r'$[a-zA-Z]\d\d\d.jpg')
for i in range(len(text_files)):
working_file = path + '\\' + text_files[i]
fin = open(working_file, 'r')
match = ''
for line in fin:
mo1 = desired_text.search(line)
if mo1 != '':
match += mo1.group()[:-7] + '_' + mo1.group()[-7:]+'\n'
fin.close()
fout = open(working_file, 'w')
fout.write(match)
fout.close()
我在第二种情况下遇到了困难,即当我有一个已经采用所需格式的条目时,例如:
205_CarlCarlson_003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
205_CarlCarlson007.jpg [size_info] [date_info] [geo_location_info] ... [other info].
我希望它跳过重命名已采用所需格式的条目的内容,并继续其余的内容。
我看过如何使用Python搜索和替换文件中的文本?一种便宜的方法,可以在大型文本文件中搜索字符串,并在Python中搜索并替换文件中的一行。这些情况似乎与搜索特定字符串有关,并使用fileinput模块将其替换为另一个字符串。我想做类似的事情,但搜索时要灵活一些。
我稍微修改了您的代码,处理了两种不同的情况,它似乎可以工作:
import os, re
path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]
desired_text1 = re.compile(r'^\d{3}_[a-zA-Z]+\d{3}.jpg')
desired_text2 = re.compile(r'^\d{3}_[a-zA-Z]+_\d{3}.jpg')
for i in range(len(text_files)):
working_file = path + '\\' + text_files[i]
fin = open(working_file, 'r')
match = ''
for line in fin:
mo1 = desired_text1.search(line)
mo2 = desired_text2.search(line)
if mo1:
match += mo1.group()[:-7] + '_' + mo1.group()[-7:]+'\n'
elif mo2:
match += mo2.group() +'\n'
fin.close()
fout = open(working_file, 'w')
fout.write(match)
fout.close()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句