2016-02-11 44 views
1

我有一个句子,我试图压缩它。然后我必须将其上传到外部文件。我的句子必须上传,而我的压缩句子在另一个文件中也一样。试图压缩一个句子,然后上传到一个文件

这是我的计划......

word_dictionary = {} 
highest = 0 
sentence = "This is a sentence and is not a very long sentence".split() 
s= "This is a sentence and is not a very long sentence" 
compressed = [] 
new = "" 
for word in sentence: 
    if word not in word_dictionary: 
     highest += 1 
    compressed.append(word_dictionary.setdefault(highest, new)) 

print(word_dictionary) 

word_dictionary = str(word_dictionary) 

fo = open("index","a+") 
fo.write(word_dictionary) 
fo.close() 

fo=open("sentence","a+") 
fo.write(s) 
fo.close() 

我想上传到文件将是...

为 “指数” ---> 1,2,3, 4,5,2,6,3,7,8,4

为“句” --->“这是一个句子,是不是一个很长的句子”

请帮帮忙,谢谢

+1

“请帮帮忙” _with what_?你有什么问题?它产生的结果与您的期望不符? – Chris

+0

它将1,2,3,4,5,6,7,8,9,10,11保存为“索引”而不是“1,2,3,4,5,2,6,3,7, 8,4 –

回答

1

这应该工作,我修改原密码,并删除highestword_dictionary,它的工作原理是,如果发生比在句子中再次追加元素index + 1,否则将追加数量最多的列表another,如果它是计数小于1,我也只好初始化another 0,以避免max()抛出异常的第一个元素

sentence = "This is a sentence and is not a very long sentence" 
s = sentence.split() 
another = [0] 

for i in s: 
    if s.count(i) < 2: 
     another.append(max(another) + 1) 
    else: 
     another.append(s.index(i) +1) 

another.remove(0) 

fo = open("index","w") 
for index in another: 
    fo.write(str(index)) 
fo.close() 

fo=open("sentence", "w") 
fo.write(sentence) 
fo.close() 
+0

感谢它现在的作品:) –

+0

刚刚编辑....不需要使用枚举 – danidee

0

您测试:

if word not in word_dictionary: 
... 

但你永远保存在字典中的任何字,而不是你保存highest计数器:

compressed.append(word_dictionary.setdefault(highest, new)) 

所以word永远不会在word_dictionaryhighest总是会增加。

+0

这听起来有点愚蠢......但我不确定你在这里告诉我什么 –

+0

你期望的原因是1,2,3,4,5,2,6,3,7 ,8,4'作为输出,是因为“是”是第二和第六个单词,因此在第二和第六个单词中是“2”。为了达到这个目的,你必须“记住”你遇到的每个新单词的第一个位置,你没有这样做,我感觉你并没有完全理解你正在尝试实现的压缩算法,也许在编码之前尝试一个笔和纸的例子。 – yurib

+0

好的,谢谢我会尝试 –

相关问题