2016-01-07 28 views
-5
loop = True 
while loop yes no maybe 
sentence is : ", myList.index(wordchosen) + 1) 

抱歉,我不得不這樣做:(

+3

如果您在這裏需要幫助,請嘗試用純英文撰寫一個連貫的問題。 – wim

+0

你好,歡迎來到StackOverflow。請花一些時間閱讀幫助頁面,尤其是名爲[「我可以詢問什麼主題?」(http://stackoverflow.com/help/on-topic)和[「我應該問什麼類型的問題避免問?「](http://stackoverflow.com/help/dont-ask)。更重要的是,請閱讀[Stack Overflow問題清單](http://meta.stackexchange.com/q/156810/204922)。您可能還想了解[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

回答

-1

我不太清楚你的要求但這個僞代碼應該是有點像你(可能)想做什麼

嘗試一些像這樣的:

  1. 得到用戶的字符串和文字,他們要搜索
  2. 將句子解析成數組(用空格解析它們)
  3. 循環遍歷它們數組並增加每次出現單詞的次數
  4. 保存這些單詞出現在另一個數組中的位置,以便以後使用或返回
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(找單詞的所有索引列表)不會,因爲它的工作將返回ite在句子

的第一個元素的位置M來獲得列表中的單詞的視覺發生只是打印改爲

print([counter + 1 for counter, ele in enumerate(sentence) if word == ele]) 
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()後彈出另一個問題:代碼似乎不起作用。這是因爲您使用身份驗證算子來檢查相等性,這並不總是產生您期望的結果。請參閱: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 

旁註:你不需要使用paranthesis各地變量:(wordchosen)

如果wordchosenmyList,請參閱其他答案,有更高效/優雅/ pythonic方法檢查。

相關問題