我正在尝试编写一个简单的程序,它将在给定目录中打开文本文件,搜索与给定模式匹配的所有字符串,并用所需的字符串替换它们,同时删除所有其他信息。我有两个 .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].
我希望它跳过重命名已经处于所需形式的条目并继续其余部分。
我看过How to search and replace text in a file using Python?和 Cheap way to search a large text file for a string , 和 Search and replace a line in a file in 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()
关于python - 在文件中搜索模式并替换找到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280883/