Python 搜索文本文件中的单词并替换为字典中的值,仅一次

Python 搜索文本文件中的单词并替换为字典中的值,仅一次,python,Python,我想获取一个文件并替换从字典中的值中获取的文本。我遇到的问题是,我只希望它在文本中运行并替换一次。我知道有几种方法可以在文本文件中进行“查找和替换”,但我似乎无法回避这个问题 如果文本文件为: TenGigabitEthernet1/1/1 config1 TenGigabitEthernet1/1/2 config2 TenGigabitEthernet1/1/3 config3 问题是,我将“TenGigabitEthernet1/1/1”替换为“interface TenGigab

我想获取一个文件并替换从字典中的值中获取的文本。我遇到的问题是,我只希望它在文本中运行并替换一次。我知道有几种方法可以在文本文件中进行“查找和替换”,但我似乎无法回避这个问题

如果文本文件为:

TenGigabitEthernet1/1/1
 config1
TenGigabitEthernet1/1/2
 config2
TenGigabitEthernet1/1/3
 config3
问题是,我将“TenGigabitEthernet1/1/1”替换为“interface TenGigabitEthernet1/1/3”,但一旦我找到字典中的下一个值,它就会再次更改。我只需要更换一次,但我找不到办法。您将在底部看到结果

from re import sub

#Based on dict, replaces key with the value on the target
def replace_content(dict_replace, target):
    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
    return target

dict_replace = {
    "interface TenGigabitEthernet1/1/1": "interface TenGigabitEthernet1/1/3",
    "interface TenGigabitEthernet1/1/2": "interface TenGigabitEthernet1/1/1",
    "interface TenGigabitEthernet1/1/3": "interface TenGigabitEthernet1/1/2"
}

file_open = open('textold.txt', 'r')
file_read = file_open.read()
file_open.close()

new_file_open = open('new_file.txt', 'w')
new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print("Old Text: ")
print(file_read)
print("New Content 1: ")
print(new_content)
我得到的结果是:

Old Text: 
interface TenGigabitEthernet1/1/1
 config 1
interface TenGigabitEthernet1/1/2
 config 2
interface TenGigabitEthernet1/1/3
 config 3

New Content 1: 
interface TenGigabitEthernet1/1/2
 config 1
interface TenGigabitEthernet1/1/1
 config 2
interface TenGigabitEthernet1/1/2
 config 3

有个主意。您可以指定一个中间散列(或某些其他唯一值)来替换值,然后在末尾替换散列

工作示例

来自重新导入子系统的

从uuid导入uuid4
#基于dict,将键替换为目标上的值
def_更换_内容(至_h,目标):
要进行检查,请将替换到_h.items():
目标=子(检查、替换、目标)
返回目标
def replace_内容(to_h、h_查找、目标):
目标=_替换_内容(目标)
对于h,在h_lookup.items()中的final_out:
目标=子(h,最终输出,目标)
返回目标
dict_replace={
“TenGigabitEthernet1/1/1接口”:“TenGigabitEthernet1/1/3接口”,
“TenGigabitEthernet1/1/2接口”:“TenGigabitEthernet1/1/1接口”,
“TenGigabitEthernet1/1/3接口”:“TenGigabitEthernet1/1/2接口”
}
to_hash={}
中间\u散列\u查找={}
要进行检查,请在dict_replace.items()中进行替换:
中间\u hash=str(uuid4())
中间\u哈希\u查找[中间\u哈希]=替换
to_hash[检查]=中间_hash
文件_read=“”接口1/1/1
配置1
接口1/1/2
配置2
接口:以太网1/1/3
配置3“
新建内容=替换内容(到散列、中间散列、文件读取)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#试验
打印(“旧文本:”)
打印(文件读取)
打印()
打印(“新内容1:)
打印(新内容)
输出

旧文本:
接口位以太网1/1/1
配置1
接口1/1/2
配置2
接口:以太网1/1/3
配置3
新内容1:
接口:以太网1/1/3
配置1
接口位以太网1/1/1
配置2
接口1/1/2
配置3
进程已完成,退出代码为0

这里有一个想法。您可以指定一个中间散列(或某些其他唯一值)来替换值,然后在末尾替换散列

工作示例

来自重新导入子系统的

从uuid导入uuid4
#基于dict,将键替换为目标上的值
def_更换_内容(至_h,目标):
要进行检查,请将替换到_h.items():
目标=子(检查、替换、目标)
返回目标
def replace_内容(to_h、h_查找、目标):
目标=_替换_内容(目标)
对于h,在h_lookup.items()中的final_out:
目标=子(h,最终输出,目标)
返回目标
dict_replace={
“TenGigabitEthernet1/1/1接口”:“TenGigabitEthernet1/1/3接口”,
“TenGigabitEthernet1/1/2接口”:“TenGigabitEthernet1/1/1接口”,
“TenGigabitEthernet1/1/3接口”:“TenGigabitEthernet1/1/2接口”
}
to_hash={}
中间\u散列\u查找={}
要进行检查,请在dict_replace.items()中进行替换:
中间\u hash=str(uuid4())
中间\u哈希\u查找[中间\u哈希]=替换
to_hash[检查]=中间_hash
文件_read=“”接口1/1/1
配置1
接口1/1/2
配置2
接口:以太网1/1/3
配置3“
新建内容=替换内容(到散列、中间散列、文件读取)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#试验
打印(“旧文本:”)
打印(文件读取)
打印()
打印(“新内容1:)
打印(新内容)
输出

旧文本:
接口位以太网1/1/1
配置1
接口1/1/2
配置2
接口:以太网1/1/3
配置3
新内容1:
接口:以太网1/1/3
配置1
接口位以太网1/1/1
配置2
接口1/1/2
配置3
进程已完成,退出代码为0

以下是一种可能的解决方案:

from re import sub

dict_replace = {
    "interface TenGigabitEthernet1/1/1": "interface TenGigabitEthernet1/1/3",
    "interface TenGigabitEthernet1/1/2": "interface TenGigabitEthernet1/1/1",
    "interface TenGigabitEthernet1/1/3": "interface TenGigabitEthernet1/1/2"
}

new_file = []
with open('textold.txt', 'r') as read_file:
    for line in read_file: 
        clean_line = line.strip() # Removes \n to make proper comparison
        if clean_line in dict_replace:
            new_file.append(dict_replace[clean_line] + '\n')
        else: 
            new_file.append(line)

with open('new_file.txt', 'w') as write_file: 
    for line in new_file: 
        write_file.write(line)
作为一些一般建议,最好避免像这样显式地打开和关闭文件和数据库等资源:

file\u open=open('textold.txt','r')
file\u open.close()

通常最好使用它,因为它们确保在离开
with
语句的上下文后自动关闭资源


将open('textold.txt',r')作为读取文件:

以下是一种可能的解决方案:

from re import sub

dict_replace = {
    "interface TenGigabitEthernet1/1/1": "interface TenGigabitEthernet1/1/3",
    "interface TenGigabitEthernet1/1/2": "interface TenGigabitEthernet1/1/1",
    "interface TenGigabitEthernet1/1/3": "interface TenGigabitEthernet1/1/2"
}

new_file = []
with open('textold.txt', 'r') as read_file:
    for line in read_file: 
        clean_line = line.strip() # Removes \n to make proper comparison
        if clean_line in dict_replace:
            new_file.append(dict_replace[clean_line] + '\n')
        else: 
            new_file.append(line)

with open('new_file.txt', 'w') as write_file: 
    for line in new_file: 
        write_file.write(line)
作为一些一般建议,最好避免像这样显式地打开和关闭文件和数据库等资源:

file\u open=open('textold.txt','r')
file\u open.close()

通常最好使用它,因为它们确保在离开
with
语句的上下文后自动关闭资源


以open('textold.txt',r')作为读取文件:

添加预期输出创建已替换单词的
集合
,但首先检查是否已在其中。添加预期输出创建已替换单词的
集合
,但检查是否已在其中。这样做了!我试图做一些类似的事情(添加一些特殊字符和替换),但遇到了问题。感谢您对我的项目非常关键的问题的快速回答@波布-Burgers@jread-没问题。我以前曾处理过这些类型的场景。祝你在这个项目上好运!成功了!我正在尝试