从位置创建句子时出现逻辑错误

时间:2017-04-01 19:57:00

标签: python

我创建了这个程序,要求在文件中输入一个位置列表,而不是将其保存为列表,并将其保存到另一个文件中,用户必须输入每个位置的单词列表。例如,如果我输入:

1 2 3 4 5 1 2 3 4 5

 this is a repeated sentence 

outpur应该是

this is a repeated sentence this is a repeated sentence 

然而,当我运行我的代码时,我得到的是位置列表

1 2 3 4 5 1 2 3 4 5

这是我的代码:

import subprocess
process_position = subprocess.Popen(["notepad","list_of_numbers.txt"])
process_position.wait()
positions = []
with open("list_of_numbers.txt","r") as f:
    positions = f.read().split()

process_words = subprocess.Popen(["notepad","list_of_words.txt"])
process_words.wait()
sentence = ""
with open("list_of_numbers.txt","r") as s:
    sentence= s.read().split()


mapping = {}

for (position, word) in zip(positions, sentence):
    mapping[position] = word


output = [mapping[position] for position in positions]

print(' '.join(output))

1 个答案:

答案 0 :(得分:0)

我觉得你很困惑。如果我理解正确,position列表是您要按顺序打印的单词位置列表。因此,您不希望将zip与来自sentence.

的字词一起sentence

相反,只需使用position数字的整数值查找result = [] for p in map(int, position): result.append(sentence[p]) print(' '.join(result)) 列表中的字词:

print(' '.join([sentence[p] for p in map(int, position)]))

或者,挤一点:

salpr = c(1, 1.2, 1.4, 1.6, 2, 5, 7, 9)
         # yyyy-mm-dd
saldt = c("2015-01-01", "2015-01-07", "2015-01-14", "2015-02-01",
          "2015-03-01", "2015-04-01", "2015-05-01", "2015-06-01" )
dd = data.frame(saldt,salpr)