这是我到目前为止的任务的第一部分,我必须制作一个程序,识别一个句子中的单个单词,将这些单词存储在一个列表中,并将原始句子中的每个单词替换为该单词的位置列表中的单词:
sentence = input("What is your sentence?: ")
sentence_split = sentence.split()
sentence2 = [0]
print(sentence)
for count, i in enumerate(sentence_split):
if sentence_split.count(i) < 2:
sentence2.append(max(sentence2) + 1)
else:
sentence2.append(sentence_split.index(i) +1)
sentence2.remove(0)
print(sentence2)
以上代码工作正常我只需要帮助完成标题中的任务部分,因为我完全陷入困境。
答案 0 :(得分:0)
也许你想做这样的事情?
sentence = raw_input("What is your sentence?: ")
sentence_lst = [a for a in sentence.split()]
sentence2 = dict(enumerate(sentence_lst))
print "sentence2 =",sentence2
一旦你掌握了每个单词的位置,你就可以根据自己的需要进行替换。
<强>输出:强>
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
What is your sentence?: hi there how are you
sentence2 = {0: 'hi', 1: 'there', 2: 'how', 3: 'are', 4: 'you'}
>>>