重新创建一个句子并输出句子中的所有单词

时间:2016-05-03 20:50:11

标签: python string

  

开发一个程序,识别句子中的单个单词,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。   例如,句子

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

有人可以在最后一点帮助我吗?

1 个答案:

答案 0 :(得分:0)

使用您生成的位置,您可以使用列表推导或简单的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])
相关问题