我的python代码应该打印句子中每个单词的数字位置,但它不起作用

时间:2017-07-11 09:53:03

标签: python

我的python代码目前看起来像这样:

list = []
lists = "" 
sentence = str(input("Enter a sentence to be translated into numbers: ")).lower()
numbers = sentence.split(' ')
list.append(lists)
print(lists)
for i,j in enumerate(sentence.split(' ')):
    print (i,j) 

我希望它根据句子中单词的位置打印一个数字

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望为给定句子中的每个单词指定一个数字,然后用其数字替换所有单词。

您可以使用:

sentence = input("Enter a sentence to be translated into numbers: ").lower().split(" ")
numbers = list(set(sentence))
result = []
for word in sentence:
    result.append(numbers.index(word))

我们在这里做的是:

  1. 从用户处获取该句子,并使用 space 作为分隔符将其拆分为列表。
  2. 从句子列表中创建一个集合。这将删除所有重复项,只留下每个单词的一个实例。然后,将该集转换为列表。
  3. 初始化一个变量result,它将保留结果。
  4. 循环翻译句子中的所有单词。
    • 对于句子中的每个单词,将其numbers中的索引附加到result
  5. 样本:

    Enter a sentence to be translated into numbers: Hello world hello world
    >>> [1, 0, 1, 0]
    
    Enter a sentence to be translated into numbers: This is a test sentence with only a single duplicate
    >>> [4, 2, 0, 6, 8, 7, 1, 0, 3, 5]