我正在研究python程序,其目标是创建一个工具,从文件中取出第一个单词并将其放在另一行的另一行中。
这是代码段:
lines = open("x.txt", "r").readlines()
lines2 = open("c.txt", "r").readlines()
for line in lines:
r = line.split()
line1 = str(r[0])
for line2 in lines2:
l2 = line2
rn = open("b.txt", "r").read()
os = open("b.txt", "w").write(rn + line1+ "\t" + l2)
但它无法正常工作。
我的问题是,我想让这个工具从文件中取出第一个单词,并将它放在另一个文件的一行中,用于文件中的所有行。
例如:
档案:1.txt:
hello there
hi there
档案:2.txt:
michal smith
takawa sama
我希望结果是:
输出:
hello michal smith
hi takaua sama
答案 0 :(得分:1)
通过使用zip功能,您可以同时循环浏览两者。然后,您可以从问候语中提取第一个单词并将其添加到名称中以写入文件。
greetings = open("x.txt", "r").readlines()
names = open("c.txt", "r").readlines()
with open("b.txt", "w") as output_file:
for greeting, name in zip(greetings, names):
greeting = greeting.split(" ")[0]
output = "{0} {1}\n".format(greeting, name)
output_file.write(output)
答案 1 :(得分:1)
是的,就像Tigerhawk所说,你想要使用zip
函数,它在同一个索引处组合来自不同迭代的元素来创建一个元组列表(每个元组都有来自每个列表的第i个索引的元素)。 / p>
示例代码 -
lines = open("x.txt", "r").readlines()
lines2 = open("c.txt", "r").readlines()
newlines = ["{} {}".format(x.split()[0] , y) for x, y in zip(lines,lines2)]
with open("b.txt", "w") as opfile:
opfile.write(newlines)
答案 2 :(得分:0)
from itertools import *
with open('x.txt', 'r') as lines:
with open('c.txt', 'r') as lines2:
with open('b.txt', 'w') as result:
words = imap(lambda x: str(x.split()[0]), lines)
results = izip(words, lines2)
for word, line in results:
result_line = '{0} {1}'.format(word, line)
result.write(result_line)
此代码无需将文件加载到内存中即可使用。