2017-02-07 2 views
0

私は文中の個々の単語を特定し、その単語の位置を出力するプログラムを作成しています。たとえば、文は:出力リスト内のリスト、文章、位置を含むプログラムにぶつかります

"私は

1 2 3 4 4 1 2をコードするのが大好きです" すべきである "私は私が愛するCODE CODE TO LOVE"

私は数字/ポジションを行うことができますが、私は個々の言葉を特定することができません。私を助けることができますか?私のコードを改善するのにも役立つでしょうか?ありがとう。私は今、この構造は@hsfzxjyが書いたものと非常に類似していることを実感

sentence = input("What is your sentence?: ") 
sentence = sentence.split() 
positions = [0] 
for count, i in enumerate(sentence): 
    if sentence.count(i) < 2: 
     positions.append(max(positions) + 1) 
    else: 
     positions.append(sentence.index(i) +1) 
positions.remove(0) 
file = open("positions.txt","w") 
positions = " ".join(map(str, positions)) 
file.write(positions) 
file.close() 
+1

私は[コードレビューSE](http://codereview.stackexchange.com)でこれを掲示することをお勧めいたします。 –

答えて

0
from collections import OrderedDict 

sentence = input("What is your sentence?: ") 
words = sentence.split() 
indices = OrderedDict() 
results = [] 
index = 1 

for word in words: 
    if word not in indices: 
     indices[word] = index 
     index += 1 
    results.append(indices[word]) 

print(' '.join(indices.keys())) 
print(' '.join(results)) 
1

は、ここに私のコードです。このコードは、しかし、TypeError例外をスローしません:

from collections import OrderedDict 

sentence = "I LOVE TO CODE CODE I LOVE" 

positions = OrderedDict() 

def get_word_index(word, index, positions): 
    position = positions.get(word) 
    if position: 
     return str(position) 
    else: 
     positions[word] = index 
     return str(index) 

indices = [get_word_index(word, index, positions) for index, word in enumerate(sentence.split(), 1)] 
print ' '.join(positions.keys()) 
# "I LOVE TO CODE" 
print ' '.join(indices) 
# "1 2 3 4 4 1 2" 
0
sentence = input("What is your sentence?: ") 
words = sentence.split() 
unique_words=[] 
for i in words: 
    if i not in unique_words: 
     unique_words.append(i) 
print unique_words 
indexes=[] 
for i in words: 
    for j in range(0,len(unique_words)): 
     if i==unique_words[j]: 
      indexes.append(j+1) 
print indexes 
関連する問題