如何将file2中的regex字符串匹配(逐个)替换为Python中类似file1中的相同匹配?

2024-10-01 07:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从一个结构化的.txt文件中复制regex匹配项,并将其粘贴到另一个类似的.txt文件中,以便从文件\u 1中找到的regex匹配项将用文件\u 1匹配项逐个替换文件\u 2中的相同匹配项?你知道吗

带有替换字符串的文本文件示例:

#TXT file 1:

randomtext_randomtext_randomtext_randomtext_new_STRING_Arandomtext_
randomtext_randomtext_new_STRING_Brandomtext_randomtext_randomtext_
randomtext_randomtext_randomtext_randomtext_randomtext_randomtext_
new_STRING_Crandomtext_randomtext_randomtext_randomtext_

#TXT file 2 (the exact same structure, but a little different strings values):

randomtext_randomtext_randomtext_randomtext_old_STRING_Arandomtext_
randomtext_randomtext_old_STRING_Brandomtext_randomtext_randomtext
_randomtext_randomtext_randomtext_randomtext_randomtext_randomtext_
old_STRING_Crandomtext_randomtext_randomtext_randomtext_

如何将使用regex找到的字符串:new \u STRING \u A、new \u STRING \u B和new \u STRING \u C从文件\u 1.txt复制到文件\u 2.txt中,以便使用相同的regex匹配:old \u STRING \u A、old \u STRING \u B、old \u STRING \u C,这样文件\u 1中的新字符串将替换文件\u 2中的旧字符串?你知道吗


Tags: 文件字符串txtnewstring粘贴oldregex
2条回答

不需要使用regex,只需要字符串比较函数

with open('file_1.txt') as f1 : 
  content = f1.readlines() 
  content = [x.strip() for x in content] 

with open('file_2.txt') as f2 : 
  content2 = f2.readlines() 
  content2 = [x.strip() for x in content] 

for line in content : 
  for line2 in content2 : 
      if 'old_STRING_A' in line2 and 'old_STRING_A' in line1 :
       line2 = line1 
      elif 'old_STRING_B' in line2 and 'old_STRING_B' in line1 :
       line2 = line1 
      elif 'old_STRING_C' in line2 and 'old_STRING_C' in line1 :
       line2 = line1 

with open('file_2.txt', 'w') as f2:
    for line in content2 : 
      f2.write(line+'\n')

使用正则表达式

import re 

with open('file_1.txt') as f1 : 
  content = f1.readlines() 
  content = [x.strip() for x in content] 

with open('file_2.txt') as f2 : 
  content2 = f2.readlines() 
  content2 = [x.strip() for x in content] 

for line in content : 
  for line2 in content2 : 
      re.sub(r'[^]?old_STRING_A[^]?','new_STRING_A',line)

with open('file_2.txt', 'w') as f2:
    for line in content2 : 
      f2.write(line+'\n')

我有这样的东西,但它不起作用。我的目标是:

  1. 使用Regex搜索文件1中的字符串
  2. 使用相同的正则表达式搜索文件2中的字符串
  3. 将文件1中找到的匹配项替换为文件2中找到的匹配项

file1 = r'C:\Users\file_1.txt'
file2 = r'C:\Users\file_2.txt'


with open(file2) as f1 : 
 content = f1.readlines() 
 content = [x.strip() for x in content] 

with open(file1) as f2 : 
 content2 = f2.readlines() 
 content2 = [x.strip() for x in content] 

for line in content : 
 for line2 in content2 : 
     re.sub(r'[^]?old_STRING_A[^]?',r'[^]?new_STRING_A[^]?',line)

with open(file1, 'w') as f2:
   for line in content2 : 
     f2.write(line+'\n')


相关问题 更多 >