【问题标题】:Recreating a sentence and outputting all the words in the sentence重新创建一个句子并输出句子中的所有单词
【发布时间】: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

标签: python string


【解决方案1】:

使用您生成的位置,您可以通过列表推导或简单的 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 循环:

reconstructed = []
for i in positions:
    reconstructed.append(x[i - 1])

【讨论】:

  • 我想要的是,当你输出句子中的所有单词时,我不希望它重复说同一个单词。
  • 例如,如果句子是“我的名字是穆萨,你好,我的名字是穆萨
  • 我真的不明白这与您的原始算法或提出的问题有什么关系,但如果您只想要独特的单词,请考虑使用 set 原语。集合不保持秩序,所以你会想要使用这样的东西pypi.python.org/pypi/ordered-set
最近更新 更多