在元组中有一个具有多个值的Dict。
newhost = {'newhost.com': ('1.oldhost.com',
'2.oldhost.com',
'3.oldhost.com',
'4.oldhost.com')
}
我想打开一个现有文件,并在该文件中搜索包含oldhosts值的行。一个文件可以有多个帐户行。在例子中 帐户:1.oldhost.com用户名 帐户:someotherhost用户名 当找到1.oldhost.com或2.oldhost.com或3.oldhost.com等的行时,我想用dict newhost.com的键替换它。
有人可以帮助我吗?搜索了很多,但没有找到正确的东西。
致谢
答案 0 :(得分:1)
也许这样可以帮助您入门
infile_name = 'some_file.txt'
# Open and read the incoming file
with open(infile_name, 'r') as infile:
text = infile.read()
# Cycle through the dictionary
for newhost, oldhost_list in host_dict.items():
# Cycle through each possible old host
for oldhost in oldhost_list:
text.replace(oldhost, newhost)
outfile_name = 'some_other_file.txt'
# Write to file
with open(outfile_name, 'w') as outfile:
outfile.write(text)
不声称这是最佳解决方案,但这对您来说应该是一个好的开始。
答案 1 :(得分:0)
要轻松找到给定旧主机的新主机,您应该转换数据结构:
list
这确实重复了新的主机名(# your current structure
new_hosts = {
'newhost-E.com': (
'1.oldhost-E.com',
'2.oldhost-E.com',
),
'newhost-A.com': (
'1.oldhost-A.com',
'2.oldhost-A.com',
'3.oldhost-A.com',
),
}
# my proposal
new_hosts_2 = {
v: k
for k, v_list in new_hosts.items()
for v in v_list}
print(new_hosts_2)
# {
# '1.oldhost-E.com': 'newhost-E.com',
# '2.oldhost-E.com': 'newhost-E.com',
# '1.oldhost-A.com': 'newhost-A.com',
# '2.oldhost-A.com': 'newhost-A.com',
# '3.oldhost-A.com': 'newhost-A.com',
# }
中的值),但是它允许您在给定旧主机名的情况下快速查找:
new_hosts_2
现在您只需要:
some_old_host = 'x.oldhost.com'
the corresponding_new_host = new_hosts_2[some_old_host]
中查找相应的新主机也许是这样的:
new_hosts_2
答案 2 :(得分:0)
谢谢您的提示。我现在想出了这个,它工作正常。
import fileinput
textfile = 'somefile.txt'
curhost = 'newhost.com'
hostlist = {curhost: ('1.oldhost.com',
'2.oldhost.com',
'3.oldhost.com')
}
new_hosts_2 = {
v: k
for k, v_list in hostlist.items()
for v in v_list}
for line in fileinput.input(textfile, inplace=True):
line = line.rstrip()
if not line:
continue
for f_key, f_value in new_hosts_2.items():
if f_key in line:
line = line.replace(f_key, f_value)
print line