gpt4 book ai didi

python - 我正在尝试用 python 压缩文件,但似乎很挣扎

转载 作者:行者123 更新时间:2023-11-28 19:14:34 24 4
gpt4 key购买 nike

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

这是一个句子,很好= 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]

关于python - 我正在尝试用 python 压缩文件,但似乎很挣扎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35326420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com