我试图获取一个文件,以便它将一个数字句子保存到列表中表格例如
这是一个句子,很好 = 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)
请帮忙,谢谢
这应该可以做你想要的:
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]
。