所以我有一个程序可以查看.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()
现在描述一个示例测试。假设有一个名为' ohdear'的.txt文件。并包含句子:"你好你好你好你好"
现在程序如下所示:
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()函数中。在此先感谢您的帮助。我被困在这一段时间......
答案 0 :(得分:0)
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
?