使用python和许多参数进行Sed

2024-04-20 12:50:45 发布

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

我有一个很大的文件,上面有这样几行:

你知道吗用户.txt你知道吗

  • 用户1:jhonny
  • 用户2:玛丽
  • 用户3:简

另一个文件包含:

你知道吗数据.txt你知道吗

  • 用户1:布朗
  • 用户3:黄色
  • 用户2:绿色

我只想制作一个文件,替换数据.txt第二个字段在用户.txt. 在决赛中,可能是这样的:

你知道吗最终.txt你知道吗

  • 你知道吗约翰尼:棕色你知道吗
  • 你知道吗简:黄色你知道吗
  • 你知道吗玛丽:绿色你知道吗

我用python编写了以下代码。你知道吗

with open("File", "r") as sources:
    lines = sources.readlines()
with open("File", "w") as sources:
    for line in lines:
        sources.write(re.sub(r'TextToReplace', 'ParameterToReplace', line))

我需要用文件上的第一个字段替换TextToReplace用户.txt参数toreplace是用户.txt. 多次使用30M+参数。你知道吗

就像一个命令sed 's/TextToReplace/ParameterToReplace/" File

  • TextToReplace=要替换的旧文本。你知道吗
  • ParameterToReplace=新文本。你知道吗

Tags: 文件数据用户txtaswithlineopen
2条回答

如果数据混合在一起,可以使用dict:

userdict={}
for i in open("users.txt","r").read().split("\n"):
    arr=i.split(":")
    userdict[arr[0]]=arr[1]
with open("final.txt","w") as f:
    for i in open("data.txt","r").read().split("\n"):
        arr=i.split(":")
        f.write("{}:{}".format(userdict[arr[0]],arr[1]))

^{} command对这类事情很有用。 假设shell理解Process Substitutions

$ join -o 1.2,2.2 -t: <(sort users.txt) <(sort data.txt)
jhonny:Brown
Mary:Green
Jane:Yellow

相关问题 更多 >