在python中查找单词的第一个实例

时间:2017-01-13 12:37:15

标签: python

我一直在编写程序来查找句子中每个唯一单词的第一个实例,但我的代码不起作用。我试图找到一个解决方案,但我似乎无法找到一个。任何帮助将不胜感激。

([^(?<=\${)(.*?)(?=})->]+)

4 个答案:

答案 0 :(得分:1)

这是否符合您的要求?

def get_word_positions(sentence):
    words = sentence.split()
    uniques = set(words)

    for word in uniques:
        yield word, words.index(word)

if __name__ == '__main__':
    sentence = input('Please enter a sentence: ')
    print(list(get_word_positions(sentence)))

运行示例

Please enter a sentence: The fox is a silly fox indeed a
[('The', 0), ('a', 3), ('is', 2), ('indeed', 6), ('silly', 4), ('fox', 1)]

答案 1 :(得分:0)

分裂是一种功能。因此,您需要使用split()

答案 2 :(得分:0)

第一步是将单词拆分为一个列表:

value

然后您可以使用字典存储每个单词的第一个出现位置:

words = sentence.split()

使用:

word_occurrences = {}
for word in words:
    word_occurrences[word] = words.index(word)

这导致:

sentence = "hi there hi to you there hi"

这可以使用以下方法整理成字典理解:

word_occurrences = {'hi': 0, 'you': 4, 'to': 3, 'there': 1}

答案 3 :(得分:0)

csentence= input("Please enter a sentence, ") 
split_sentence=csentence.split() # added brackets & changed sentence to csentence
word_index=[]
words=[]
for x,y in enumerate(split_sentence):   
    print(x,y)   
    if y not in words:
        words.append(y)        
        word_index.append(x)

print(word_index)
相关问题