我有两个文本文件。一个名为' textfile'另一个名为' textfile1'。这两个文本文件包含构成句子的单词,另一个包含构成原句中句子的单词的位置。两者都来自两个列表。
sentence = "This and that, and this and this."
textfile = ['This', 'and', 'that,', 'this', 'this.'
textfile1 = [0, 1, 2, 1, 3, 1, 4]
我使用列表重新创建了句子。但是想要使用文本文件重新创建它。我试过了:
wrd = []
num = []
textfile = open ("words.txt", "r")
for row in textfile:
wrd.append(row.split())
textfile1 = open ("positions.txt", "r")
for i in textfile1:
num.append(int(i.strip()))
recreated = ' '.join(wrd[pos] for pos in num)
textfile2 = open ("recreated.txt", "wt") #opening a new text file in write mode
textfile2.write (recreated)
textfile2.close() #closing the text file
然而这不起作用。我想使用两个文本文件的内容重新创建原始句子。谢谢。
答案 0 :(得分:1)
嗨,我看到两个错误。
首先你的循环遍历行而不是单词
for row in textfile:
wrd += row.split()
是获取所有单词的好方法。
然后你将一些字符串附加到num,而不是int。
for i in textfile1:
row = [int(j) for j in i.split()]
num += row
是一种拥有整数索引并坚持代码的方法,即使我会考虑重构它。
这是一个想法:
words = list()
num = list()
with open("words.txt", "r") as f:
for line in f:
words += line.split()
with open("positions.txt", "r") as f:
for line in f:
num += [int(i) for i in line.split()]
recreated = ' '.join(words[pos] for pos in num)
with open("recreated.txt", "wt") as f:
f.write(recreated)
答案 1 :(得分:0)
您从textfile1
读取字符串(如果您确实从文件中读取它们,那么与您在textfile1
列表中发布的代码不同)。简短版本可能如下:
wrd = open('textfile', 'r').read().strip().split()
num = [int(token) for token in open('textfile1', 'r').read().strip().split()]
with open('textfile2', 'w') as f:
f.write(' '.join([wrd[i] for i in num))
答案 2 :(得分:0)
如果您的文件看起来像这样
This
and
that
this
this
你可以这样做,
file1 = open('file.txt', 'r')
print list(l.strip() for l in file1)
哪些打印,
['This', 'and', 'that', 'this', 'this']
如果您有这样的文件,
This and that this this
你可以,
file1.readline().split()
这基本上给出了相同的输出。并且您可以为其他文件执行相同的操作,并获得您在问题中指定的两个列表。现在,您可以继续重新创建句子,
textfile = ['This', 'and', 'that,', 'this', 'this.']
textfile1 = ['0', '1', '2', '1', '3', '1', '4']
recreated = ' '.join(textfile[int(pos)] for pos in textfile1)
最后将其写回另一个文件,
open("recreated.txt", "wt").write(recreated)