第一个文件看起来像这样:
writing
writing
writing
writing
eating
eating
eating
doing
doing
doing
...
第二个文件看起来像这样:
writing write wrote written
eating eat ate
doing do does done
...
所以基本上,我需要将第二个文件中的单词(逐字逐句)添加到第一个文件的每一行(每行依次一个单词)并将其保存在第三个文件中,如下所示:
writing writing
writing write
writing wrote
writing written
eating eating
eating eat
eating ate
doing doing
doing do
doing does
doing done
...
我尝试了这段代码,但它没有完成这项工作:
infile = open("first.txt", 'r') # open file for reading
infile2 = open("second.txt", 'r') # open file for reading
outfile = open("third.txt","w") # open file for writing
line = infile.readline()
line2 = infile2.readline() # Invokes readline() method on file
while line:
outfile.write(line.strip(' ')+line2.strip("\n")+'\n')
line = infile.readline()
line2 = infile2.readline()
infile.close()
outfile.close()
infile2.close()
答案 0 :(得分:1)
要将两个文件放在一起,我会完全阅读并以不同的方式拆分它们以获取您的文字,然后将它们放在一起。
加载第一个文件。在第一个文件中,每行有一个单词,因此请读取每一行并将其存储到列表中:
words_first = []
with open('first.txt') as f:
for line in f:
words_first.append(line)
加载第二个文件。第二个文件每行有多个单词和多行,因此请读取每一行并将其拆分为单词并将其存储到列表中:
words_second = []
with open('second.txt') as f:
for line in f:
words_second.extend(line.split(" "))
存储到新文件中。现在你有两个单词列表,所以使用zip将它们打包在一起并将它们存储到文件中:
with open('third.txt', 'w') as f:
for first, second in zip(words_first, words_second):
f.write("{0} {1}\n".format(first, second))
此版本使用split()
(分割所有空格(换行符和空格)),因此您可以拆分完整文件并获取由换行符和空格分隔的所有单词的列表:
def get_words(file_path):
with open(file_path) as f:
return f.read().split()
with open('third.txt', 'w') as f:
for first, second in zip(get_words("first.txt"), get_words("second.txt")):
f.write("{0} {1}".format(first, second))
答案 1 :(得分:1)
为什么你甚至需要第一个文件?
infile2 = open('second.txt', 'r')
outfile = open('third.txt', 'w')
for line in infile2:
words = line.split()
outfile.write('\n'.join('%s %s' % (words[0], w) for w in words) + '\n')
outfile.close()
infile2.close()