重新生成一个句子并输出句子中的所有单词

2024-06-16 15:03:51 发布

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

Develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list. For example, the sentence

MY NAME IS MY NAME IS MY NAME IS 

The sentence can be recreated from the positions of these words in this list using the sequence 1,2,3,1,2,3,1,2,3

到目前为止,我得到的是:

sentence = input("Please enter a sentence that you would like to recreate")
x = sentence.split()

positions = [0]

for count, i in enumerate(a):
    if x.count(i) < 2:
        positions.append(max(positions) + 1)
    else:
        positions.append(x.index(i) +1)

positions.remove(0)
print(positions)

这重新创建了位置,但我需要做的是输出句子中的所有单词。在

例如,如果我写了一个句子Leicester city are champions of the premier league the premier league is the best,我希望程序输出这个句子包含单词Leicester, city, are, champions, of, the, premier, league, is, best。在

有人能帮我最后一点忙吗?在


Tags: ofthenameinthatismysentence
1条回答
网友
1楼 · 发布于 2024-06-16 15:03:51

使用您生成的位置,您可以通过列表理解或简单的for循环获取所需的列表部分。这里的关键是,当存储的数字以1开头时,python索引从0开始。然后可以使用字符串的join函数以逗号打印。在

sentence = "Leicester city are champions of the premier league the premier league is the best"
x = sentence.split()

positions = [0]

for count, i in enumerate(x):
    if x.count(i) < 2:
        positions.append(max(positions) + 1)
    else:
        positions.append(x.index(i) +1)


positions.remove(0)

reconstructed = [x[i - 1] for i in positions]
print(", ".join(reconstructed))

或者,使用for循环:

^{pr2}$

相关问题 更多 >