我已经远距离搜索但找不到我的任务的解决方案。我需要能够从输入中获取单词的位置,然后将其和单词(删除重复项)保存到记事本文件中。然后,我需要能够将这些位置带回来并重新创建句子。然而,这必须完成Python。为了更清楚,我将使用我已编写的代码使用示例:
- 输入 -
Would you like to compress or decompress a file? c/d: C
Please type your string using only letters and punctuation: the dog was a dog that jumped over a log
Positions saved to file. Ending code
- 结果 -
1 2 3 4 2 5 6 7 4 8
the dog was a that jumped over log
我遇到的问题是我无法从这些数字或单词重新创建句子,因为我不明白如何完成这个。到目前为止,我最后一点的代码如下:
#
posFile = open ("positions.txt", "r") #Opens and reads the file with the positions saved
posFileStr = posFile.read()
wordFile.close()
posFile.close()
#
word_list = (wordList) #Opens and reads the file with the unique words saved
word_index = (posFileStr)
recreated = ' '.join([word_list[i-1] for i in word_index])
positions = [wordList.index(word) for word in sentence]
print (recreated)
print (positions)
答案 0 :(得分:0)
您的代码不完整,因此无需修复/建议。
这条线对我来说很好看:
recreated = ' '.join([word_list[i-1] for i in word_index])
表示word_index缺少单词。
注意:上面的列表理解不需要括号。如果省略它们,您将获得一个连接迭代的生成器,而无需先分配全新的列表。示例:' '.join(a for a in b)
这是一个解决方案。希望它能帮助您在代码中看到错误。
In [3]: s = 'the dog was a dog that jumped over a log'
In [17]: i = 1
...: d = {}
...: words = []
...: sentence = []
...: for w in s.split():
...: if w not in d:
...: d[w] = i
...: i += 1
...: words.append(w)
...: sentence.append(d[w])
...:
In [18]: words
Out[18]: ['the', 'dog', 'was', 'a', 'that', 'jumped', 'over', 'log']
In [19]: sentence
Out[19]: [1, 2, 3, 4, 2, 5, 6, 7, 4, 8]
In [20]: ' '.join(words[i - 1] for i in sentence)
Out[20]: 'the dog was a dog that jumped over a log'
In [21]: