loop = True
while loop yes no maybe
sentence is : ", myList.index(wordchosen) + 1)
答案 0 :(得分:0)
我认为这就是你想要的
while True:
sentence = input('Enter a sentence:\n')
sentence = sentence.lower().split()
print(sentence)
word = input('Enter a word you want to find in the sentence:\n')
print([counter for counter, ele in enumerate(sentence) if word == ele])
decision = input('Yes or no to exit or continue')
decision.lower
if decision == 'yes':
continue
else:
break
这将返回您在句子中寻找的单词的所有索引的列表 sentence.index()将无效,因为它将返回句子中第一个元素的项位置
要在列表中直观地显示单词,只需将打印更改为
print([counter + 1 for counter, ele in enumerate(sentence) if word == ele])
答案 1 :(得分:0)
您的问题非常令人困惑,因为它只包含未作为代码设置的代码。你应该总是包括一些简单的英文描述问题。我试着猜测:)
您的代码有一些缩进问题,它不会这样运行。
您使用input()
函数,该函数在输入句子时失败:
write a sentence
tre sdf fre dfg
Traceback (most recent call last):
File "bin/tst.py", line 14, in <module>
sentence = input()
File "<string>", line 1
tre sdf fre dfg
^
SyntaxError: invalid syntax
考虑使用
raw_input()
函数进行常规输入 用户。
从input()
切换到raw_input()
后会弹出另一个问题:代码似乎无效。这是因为您使用is
身份运算符来检查相等性,这不会产生您期望的结果。请参阅:Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
将is
切换为==
后,代码可能会按照您的意图运行:
write a sentence
this is the input sentence
this is the input sentence
choose a word from the sentence that you would like to find the word postion of
sentence
('word position for your sentence is : ', 5)
write a sentence
旁注:您不需要对变量使用限制:(wordchosen)
。
有更高效/优雅/ pythonic的方式来检查wordchosen
中是否myList
,请参阅其他答案。
答案 2 :(得分:-1)
我不太确定你在问什么,但是这个伪代码应该有点像你(可能)想做的那样。
尝试这样的事情: