-3

使用文件创建句子

sentence = 'the cat sat on the cat mat'

indivdual_words = ['the', 'cat', 'sat', 'on', 'mat']
positions = [1, 2, 3, 4, 1, 2, 5]

f = open('word_file.txt', 'w+')
f.write(str(words))
f.close()

f = open('pos_file.txt', 'w+')
f.write(str(positions))
f.close()

程序应将 1 视为 the ,将 2 视为 cat 等

4

3 回答 3

1

由于您将所有内容都存储为字符串,因此您最终会得到与有效 python 表达式匹配的文件内容。您可以使用ast.literal_eval从字符串表示中获取实际的 python 对象。

from ast import literal_eval

with open('word_file.txt') as f:
    data = f.read().strip()
    words = ast.literal_eval(data)

with open('pos_file.txt') as f:
    data = f.read().strip()
    pos = ast.literal_eval(data)

然后做你之前做的相反的事情。

result = " ".join([words[i-1] for i in pos])
于 2017-01-24T20:34:44.377 回答
1

由于您正在转储列表的表示形式,因此最好的方法是使用ast.literal_eval

import ast

with open('word_file.txt') as f:
    indivdual_words = ast.literal_eval(f.read())
with open('pos_file.txt') as f:
    positions = ast.literal_eval(f.read())

然后使用列表理解重新创建句子以按顺序生成单词,并用空格连接:

sentence = " ".join([indivdual_words[i-1] for i in positions])

结果:

the cat sat on the cat mat
于 2017-01-24T20:35:08.563 回答
0

创建可读写的文件对象后(w 表示 word 文件,n 表示索引文件):

1) 遍历单词文件对象,将每个单词附加到一个空列表中

2)遍历索引文件对象,通过索引文件对象中的索引将单词列表中的每个单词分配给临时变量单词,然后将该单词添加到您尝试形成的原始空句子中。

word_list = []
for word in w:
wordlist.append(word)

sentence = ''
for index in n:
word = wordlist[index]
sentence+= word
sentence+= ' '
于 2017-01-24T20:52:27.313 回答