我正在尝试替换文本值,如下所示。我有2个文本文件
1 - input.txt
abc = 123
xyz = 456
pqr = 789
2 - content.txt
AAA = abc
XXX = xyz
PPP = pqr
现在我需要读取input.txt文件并使用input.txt值替换content.txt文件中的值并获取以下输出文件。
3 - new.txt
AAA = 123
XXX = 456
PPP = 789
我该怎么做?
答案 0 :(得分:1)
首先按以下方式将文件内容读入2个数组
file1handle = open('filename1', 'r')
file1 = file1handle.readlines()
file2handle = open('filename2', 'r')
file2 = file2handle.readlines()
file2handle.close()
file2handle.close()
然后迭代内容并尝试找到与变量名称和赋值的匹配,并按以下方式将值放入第三个数组
for item in file1:
name, value = item.split(' = ')
for item2 in file2:
name2, assignment = item2.split(' = ')
#Here we are trying to check which name is to be assigned which value
if assignment == name:
val = name2+'='+value
file3.append(val)
然后按照以下方式将内容写入文件
filehandle3 = open('filename3', 'w')
for line in file3:
filehandle3.write(line)
filehandle3.close()
答案 1 :(得分:1)
这可能会对你有帮助,
_input = {}
with open('input.txt', 'r') as f:
s = f.read()
_input = dict((a.split(' = ')[0], int(a.split(' = ')[1])) for a in s.split('\n'))
_content = {}
with open('content.txt', 'r') as f:
s = f.read()
_content = dict((a.split(' = ')[0], a.split(' = ')[1]) for a in s.split('\n'))
for key in _content:
_content[key] = _input[_content[key]]
结果:
In [18]: _content
Out[19]: {'AAA': 123, 'PPP': 789, 'XXX': 456}
答案 2 :(得分:0)
import re
class Defs:
def __init__(self, defs_file):
self._defs = {}
with open(defs_file) as df:
line_num = 0
for l in df:
line_num += 1
m = re.match(r'\s*(\w+)\s*=\s*(\S+)\s*', l)
assert m, \
"invalid assignment syntax with \"{}\" at line {}".format(
l.rstrip(), line_num)
self._defs[m.group(1)] = m.group(2)
def __getitem__(self, var):
return self._defs[var]
@property
def dict(self):
return self._defs
class Replacer:
def __init__(self, defs):
self._defs = defs
def replace_with_defs(self, context_file, output_file):
with open(context_file) as context, open(output_file, 'w') as output:
for line in context:
string_repl = re.sub(r'\b(\w+)\b',
lambda m: self._defs.dict.get(m.group(1)) or m.group(1), line)
output.write(string_repl)
def main():
defs = Defs('input.txt')
repl = Replacer(defs)
repl.replace_with_defs('context.txt', 'output.txt')
if __name__ == '__main__':
main()
为了描述上面发生的事情,Defs
类采用defs_file
这是input.txt赋值,并将它们存储在将每个变量名绑定到关联值的dict中。 Replacer
类句柄接受一个Defs
对象,并使用它们迭代context_file
中的每一行,即context.txt,并替换任何令牌(假设令牌是变量名)在Defs
对象中指定的与之关联的值,并将其写入文件output_file
,即output.txt。如果令牌在Defs
对象中不作为有效变量名存在,则默认为按原样写入令牌。
答案 3 :(得分:0)
使用pandas怎么样:使用大文件时它更短,更容易阅读和更快。
import pandas as pd
import numpy as np
input=pd.read_csv("input.txt",sep="=",header=None,usecols=[1])
content=pd.read_csv("content.txt",sep="=",header=None,usecols=[0])
foo=np.hstack(([content.values,input.values]))
new=pd.DataFrame(foo)
new.to_csv("new.txt",index=False,sep="=",header=None)