2016-02-10 81 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

非常感謝你:) –