我想创建一个代码,要求用户输入纯文本文件中的位置列表,将用户在文本文件中输入的位置保存为列表,而不是要求用户输入每个位置所代表的单词(与位置列表相同的顺序)结束重新创建句子。但是,当我运行此代码时:
import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
p =open("list_of_numbers.txt","r")
l = p.read()
p.close()
positions = list(l)
subprocess.Popen(["notepad","list_of_words.txt"])
s = open("list_of_words.txt","r")
s.read()
s.close()
sentence = str(s)
print (sentence)
mapping = {}
words = sentence.split()
for (position, word) in zip(positions, words):
mapping[position] = word
output = [mapping[position] for position in positions]
print(' '.join(output))
我跑
1 2 3 4 5 1 2 3 4 5
作为职位列表
这是单词列表:
this is a repeated sentence
输出应为:
this is a repeated sentence this is a repeated sentence
但是我得到了
"key error:3"
我认为他们的问题是我没有正确地将位置列表存储到列表中但我不确定。有人可以帮帮我吗?
答案 0 :(得分:0)
尝试这个
import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as p:
l = p.read()
positions = l.split() # see you had to create list by spliting the string
subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as s:
sentence = s.read() # you had to assign the string to variable
print (sentence)
mapping = {}
words = sentence.split()
for position, word in zip(positions, words):
mapping[position] = word
output = [mapping[position] for position in positions]
print(' '.join(output))
但也可能是
import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
positions = pos_file.read().spllit()
subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
words = sentence_file.read().split()
mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]
print(' '.join(output))