因此,我有一个程序,可以查看.txt文件中的一个句子。然后,该程序将查找句子中每个单词的位置以及句子中唯一的单词。这两个列表在程序中输出,然后程序尝试根据句子中唯一的单词和句子中单词的位置在.txt文件中重新创建原始句子,然后在程序中输出。我到目前为止掌握的代码如下所示:
import json
import os.path
def InputFile():
global compfilename
compfilename = input("Please enter an existing compressed file to be decompressed: ")
def Validation2():
if compfilename == (""):
print ("Nothing was entered for the filename. Please re-enter a valid filename.")
Error()
if os.path.exists(compfilename + ".txt") == False:
print ("No such file exists. Please enter a valid existing file.")
Error()
def OutputDecompressed():
global words
global orgsentence
newfile = open((compfilename)+'.txt', 'r')
saveddata = json.load(newfile)
orgsentence = saveddata
words = orgsentence.split(' ')
print ("Words in the sentence: " + str(words))
def Uniquewords():
for i in range(len(words)):
if words[i] not in unilist:
unilist.append(words[i])
print ("Unique words: " + str(unilist))
def PosText():
global pos
find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
pos = (list(map(lambda sentence: find [sentence], words)))
return (pos)
def Error():
MainCompression()
def OutputDecompressed2():
for number in pos:
decompression.append(orgsentence[int(number)-1])
finalsentence = (" ".join(decompression))
print ("Original sentence from file: " + finalsentence)
def OutputText():
print ("The positions of the word(s) in the sentence are: " + str(pos))
def MainCompression():
global decompression
decompression = []
global unilist
unilist = []
InputFile()
Validation2()
OutputDecompressed()
Uniquewords()
PosText()
OutputText()
OutputDecompressed2()
MainCompression()现在描述了一个示例测试。假设有一个.txt文件名为“ohdear”,其中包含以下句子:“你好”
现在,程序如下所示:
Please enter an existing compressed file to be decompressed: ohdear
Words in the sentence: ['hello', 'hello', 'hello', 'hello']
Unique words: ['hello']
The positions of the word(s) in the sentence are: [1, 1, 1, 1]
Original sentence from file: h h h h正如你所看到的,原来的句子不是根据句子中独特的词和词的位置重新创造出来的--奇怪的是,4小时才被显示出来。有人能帮我解决这个错误吗?因为我不知道如何从句子中独特的单词和单词的位置重新创建原来的句子。问题在于OutputDecompressed2()函数。谢谢你提前提供帮助。我被困在这上面有一段时间了..。
发布于 2017-04-02 11:26:26
words = orgsentence.split(' ')这意味着words是一个字符串列表,而orgsentence只是一个大字符串。但之后你会得到:
orgsentence[int(number)-1]这只是一个角色。我宁愿去找words[int(number)-1]。
另外:
find = dict((sentence, words.index(sentence)+1) for sentence in list(words))只需给出每个“sentence”的第一次出现,因为.index就是这样做的,因此您有了输出:
The positions of the word(s) in the sentence are: [1, 1, 1, 1]这显然是错误的。
顺便说一句,sentence是一个可怕的变量名,为什么不word?
https://stackoverflow.com/questions/43167713
复制相似问题