我试图在python中压缩文件,似乎正在挣扎

时间:2016-02-10 21:35:26

标签: python python-2.7 python-3.x

我试图获取一个文件,以便将数字中的句子保存到列表中 例如。

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

看,is = 2并重复如上所示

这是我的代码中的一部分...

j = sentence

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

请帮忙,谢谢

1 个答案:

答案 0 :(得分: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]