坚持一个涉及列表中的列表,句子和位置的程序

时间:2017-02-07 11:24:49

标签: python python-3.x

所以我创建了一个程序,用于识别句子中的单个单词并打印出单词的位置。例如,句子:“我喜欢我爱的代码”应输出

“我喜欢代码

1 2 3 4 4 1 2“

我可以做数字/位置,但我无法识别单个单词。你能救我吗?你能帮我改进我的代码吗?感谢。

这是我的代码:

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()

3 个答案:

答案 0 :(得分:1)

我现在意识到这个结构与@hsfzxjy写的很相似。但是,此代码不会抛出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"

答案 1 :(得分: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))

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