如何使用for循环找到在字符串中出现多次的单词的单词位置

时间:2016-01-07 18:30:12

标签: python

loop = True
while loop yes no maybe
sentence is : ", myList.index(wordchosen) + 1)

抱歉,我不得不这样做:(

3 个答案:

答案 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

来自input() documentation

  

考虑使用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)

我不太确定你在问什么,但是这个伪代码应该有点像你(可能)想做的那样。

尝试这样的事情:

  1. 获取要搜索的用户字符串和字词
  2. 将句子解析为数组(用空格解析)
  3. 循环遍历数组,并在每次出现单词时增加计数
  4. 将这些单词出现的位置保存到您以后可以使用或返回的另一个数组中