2016-05-14 11 views
-2

入力文から入力単語の位置を探すように求められましたが、使用方法を理解する上で問題があります.splitとlistsを一緒に列挙します。これは私がこれまで持っているものです。.split、enumerate、およびlistsを使用して文中の単語の位置を見つける方法

sntc=str(input("Please input a sentence with no punctuation.")) 
wrd=str(input("Please input a word from that sentence.")) 
words=sntc.split 
list(enumerate(sntc)) 
for x in y in enumerate: 
    if x==(wrd): 
     print ("The chosen word is in postion(s):",x+1) 

答えて

0

これは、あなたが探しているソリューションです - シンプルで効率的な:

列挙し、リストを使用して
sntc = input("Please input a sentence with no punctuation. ") 
wrd = input("Please input a word from that sentence. ") 
words = sntc.split() 
print(words.index(wrd) + 1) 

sntc = input("Please input a sentence with no punctuation. ") 
wrd = input("Please input a word from that sentence. ") 
words = sntc.split() 
e = list(enumerate(sntc)) 
for ind, word1 in e: 
    if word1 == wrd: 
     print("The chosen word is in postion(s):", ind+1) 

あなたのコードいくつかの理由でうまくいきません:

1)関数の戻り値を変数に代入したい場合は、その戻り値ではなく機能そのものを取得する機能:

>>> words = sntc.split 
>>> words     # the variable words now contains a function 
<built-in method split of str object at 0x0243F4D0> 
>>> words = sntc.split() 
>>> words     # and now a list that you want 
['text', 'text', 'text'] 

2)それはあなたが任意の変数にlist(enumerate(sntc))を割り当てていなかった機能ではなく反復可能 だとしてあなたは、enumerateを反復処理することができません、そして、私はあなたがそれを反復することを意図かなり確信している:

e = list(enumerate(sntc)) # now you can iterate over e 
for ind, word in e: 
    print(ind, word) 
1

あなたはstrへの入力を変換する必要はありません。それはすでに文字列です。

wordsはあなたの意見ではありません。これはすべてsplitメソッドへの参照です。あなたは実際にはsplitと呼ぶことはありません。

-

>>> a_string = "Look a string" 
>>> print(a_string.split) 
>>> <built-in method split of str object at (memory address)> 

分割を呼び出すのに対し、我々は持っている:

>>> print(a_string.split()) 
>>> ['Look', 'a', 'string'] 

それはあなたがwords = sntc.split以下列挙し、すべてを達成しようとしているまさに不明です。私は実際にsntcを列挙し、指定されたwrdがこの分割リストの項目と一致するかどうかをチェックしたいと思う。別の問題は、反復可能で反復可能と項目に戻りインデックスを列挙し、

あります、ここでのインデックス(位置)はちょうどこのリスト内の位置になります(ワード)+ 1

ない実際の位置文中の

-

>>> sntc = input("Please input a sentence with no punctuation: ") 
Please input a sentence with no punctuation: Look a sentence 
>>> wrd = input("Please input a word from that sentence: ") 
Please input a word from that sentence: a 
>>> words = sntc.split() 

単語= ここでは 'a'の位置は1です。あなたが実際に欲しい

>>> for i, word in enumerate(words): 
...  if word == wrd: 
...   print("Chosen word is in position %d" % (i + 1)) 
... 
Chosen word is in position 2 #Position of 'a' + 1 

は次のとおりです。

for word in words: 
    if word == wrd: 
     print("Position is %d" % sntc.index(word)) 
0

リストの使用リスト名の要素の位置をしたい場合。

a = ["hello", "world"] 
a.index("hello") 
returns 0 
0

次のアプローチは、.split、enumerate、およびlistsを使用して、文中の単語の位置を見つけるのに役立ちます。

sentence = 'I like movie'  # given sentence 
sentence = sentence.split()  # spliting sentence to split 
wrd = 'like'     # a given word to find position in the sentence 
[i for i, w in enumerate(sentence) if w==wrd] 
関連する問題