Python 或 Bash - 如何在两个句子中间添加文件中列出的单词并将输出放入另一个文件?

我不知道如何定义变量“set”和“”,然后在“file2”中为“file1”中列出的每个名称添加最后一个单词“username”和“admin”之前放置一个名称和另一个“”。

file1 = [/home/smith/file1.txt]

file2 = [/home/smith/file2.txt]

file3 = file1 + file2

例子:

[file1 - 名称]

史密斯

杰瑞

夏天

亚伦

[file2 - 句子]

设置用户名

设置管理员

[文件 3 - 输出]

设置史密斯用户名

设置史密斯管理员

设置杰瑞用户名

设置杰瑞管理员

设置夏季用户名

设置夏季管理员

设置亚伦用户名

设置亚伦管理员


慕码人2483693
浏览 140回答 4
4回答

猛跑小猪

像这样的东西,也许..names = file("/home/smith/file1.txt").readlines()commands = file("/home/smith/file2.txt").readlines()res = []for name in names: for command in commands:   command = command.split(" ")   res.append(" ".join([command[0],name,command[1]]))file("/home/smith/file3.txt","w").write("\n".join(res))我敢肯定这不是最漂亮的方式,但应该可以。但是你为什么要做这样的事情......?

慕森卡

你能更具体地谈谈你的问题吗?你已经尝试过什么了吗?如果是这种情况,请分享。在我看来,您可以打开 file2,读取每一行,在空格上拆分两个单词(例如,将其添加到列表中)。然后,您可以为您在该列表中创建的每组单词创建一个新字符串。循环 file1 中的每一行。对于 file1 中的每一行:从 file2 中取出第一个单词,添加一个空格。从 file1 添加实际行。最后,您添加另一个空格和第二个单词 from。例如,您现在有一个新字符串,您可以将其附加到新文件中。您可能应该将该字符串附加到创建字符串的同一循环中的新文件中。但是话又说回来,我不确定这是否是您问题的答案。

精慕HU

仅使用实用程序的另一种解决方案:join -1 2 -2 3 file1 file2 | awk '{printf "%s %s %s\n", $2, $1, $3}' > file3

手掌心

在 Bash 中试试这个,它回答了你的问题#!/bin/bashfile1=".../f1.txt"file2=".../f2.txt"file3=".../f3.txt"while read p1; do&nbsp; &nbsp; &nbsp; &nbsp; while read p2; do&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; word1=$(echo $p2 | cut -f1 -d' ')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; word2=$(echo $p2 | cut -f2 -d' ')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo " $word1 $p1 $word2" >> $file3&nbsp; &nbsp; &nbsp; &nbsp; done < $file2done < $file1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python