【发布时间】:2023-11-20 08:58:01
【问题描述】:
开发一个程序来识别句子中的单个单词,将这些单词存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。 比如句子
MY NAME IS MY NAME IS MY NAME IS可以使用序列 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。
有人可以帮我解决最后的问题吗?
【问题讨论】:
-
这个问题有问题陈述、代码、期望的输出和问题本身。好帖子,@Musa,这(几乎)是我们对新用户的期望,干杯!
-
print(", ".join(x))将打印列表x的内容,每个单词之间使用逗号和空格 - 这就是您想要的吗? -
您的示例不起作用。
a是什么? -
抱歉 a 本来就是 x