制作一个将一句话压缩成独特单词和位置的程序

2024-10-03 06:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用Python编写一个程序,它将用户输入的句子压缩成一个独特的单词和位置列表。例如,“不要问你的国家能为你做什么,而要问你能为你的国家做些什么”这句话将被压缩为“不要问你的国家能为你做什么”,而位置将是“12345678913967845”。在

然后从这些独特的句子位置重新创造出来。在

我的问题是我现在卡住了,我有压缩部分工作,但我真的不知道如何解压缩句子。我的意思是我知道如何阅读文本文件,但不知道如何通过独特的单词和位置来重新创建原始句子。在

以下是我当前的代码:

###This section will compress the sentence(s)###
        txt_file = open("User_sentences.txt","wt")
        user_sntnce = input(str("\nPlease enter the sentence(s) you would\nlike compressed.\n\n➜ "))
        user_sntnce_list = user_sntnce.split(" ")                     
        print(user_sntnce_list)

        for word in user_sntnce_list: 
            if word not in uq_words:
                uq_words.append(word)
        txt_file.write(str(uq_words) + "\n")

        for i in user_sntnce_list:
            positions = int(uq_words.index(i) + 1)
            index.append(positions)
            print(positions)
            print(i)
            txt_file.write(str(positions))
    txt_file.close()
###This section will DECOMPRESS the sentence(s)###
    if GuideChoice == "2":
        txt_file = open("User_sentences.txt","r")
        contents = txt_file.readline()
        words = eval(contents)
        print(words)
        txt_file.close()

感谢任何帮助!在


Tags: thetxt国家sentencelist句子wordfile
1条回答
网友
1楼 · 发布于 2024-10-03 06:30:10

您可以按空格将句子拆分为一个列表,然后通过该列表枚举并将位置存储在defaultdict中,这将允许您为每个单词创建一个位置列表(而且,您不需要将空格传递给split):

from collections import defaultdict

positions = defaultdict(list)
user_sentence = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'
sentence = user_sentence.split()
for position, word in enumerate(list(sentence), start=1):
    positions[word].append(position)

结果是:

^{pr2}$

相关问题 更多 >