简体   繁体   English

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

[英]Recreating a sentence and outputting all the words in the sentence

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 可以使用序列1,2,3,1,2,3,1,2,3从该列表中的这些单词的位置重新创建该句子

This is what I have so far: 这是我到目前为止:

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)

This recreates the positions but what I need to do is output all the words that are in the sentence. 这会重新创建位置,但我需要做的是输出句子中的所有单词。

For example, if I wrote the sentence Leicester city are champions of the premier league the premier league is the best , I would want the program to output that the sentence contains the words Leicester, city, are, champions, of, the, premier, league, is, best . 例如,如果我写的句子Leicester city are champions of the premier league the premier league is the best ,我希望程序输出句子包含Leicester, city, are, champions, of, the, premier, league, is, best

Can somebody help me in this last bit? 最后一点有人可以帮助我吗?

Using the positions you generated, you can grab the parts of the list you want with a list comprehension or a simple for loop. 使用您生成的位置,您可以使用列表推导或简单的for循环来获取所需列表的各个部分。 The key here that while the numbers you are storing begin with 1 , python indices start at 0 . 这里的关键是,当您存储的数字以1开头时,python索引从0开始。 You can then use the join function of strings to print with commas. 然后,您可以使用字符串的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))

Alternatively, with a for loop: 或者,使用for循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM