2016-02-10 44 views
3

我正在试图获取一个文件,以便它从表格中保存一个数字为 的文章,例如,我正试图压缩python文件,似乎正在努力

这是一个句子,也是很好= 1,2,3,4,5,2,6

看,是= 2并且重复如上所示

这是来自部分我代码...

j = sentence 

for position, word in enumerate(sentence): 
    if word in word_dictionary: 
     word_dictionary.append(position) 

请帮忙,谢谢

回答

0

这应该做你想要什么:

word_dictionary = {} # start with empty dictionary 
highest = 0 # and set our counter to 0 
sentence = "this is a sentence and is good".split() 
compressed = [] 
for word in sentence: 
    if word not in word_dictionary: 
     highest += 1 # new word, so we need a new number 
    # append the word number, and if it's not in the dictionary, 
    # set it, too 
    compressed.append(word_dictionary.setdefault(word, highest)) 

这正确设置compressed[1, 2, 3, 4, 5, 2, 6]

+0

非常感谢你:) –