如何在字符串/列表中查找单词的位置?

时间:2016-06-28 15:28:58

标签: python string list position word

我正在编写一个函数,用户输入一个单词,然后输入一个字符串,该函数识别字符串中所有出现的位置和该单词的位置(尽管它实际上已转换为中间列表)。

我目前的代码只是识别单词的第一次出现,而不是更进一步。如果单词是字符串中的第一个单词,则它也不会识别单词,返回空列表。它还会说单词的实际位置 - 1,因为第一个单词被计为零。

我试图通过两种方式来解决这个问题,第一种是aString.insert(0, ' '),第二种是for i in __: if i == int: i += 1。这些都不奏效。

此外,在执行.insert时,我尝试在空间中放置一个字符,而不是一个空格(因为此部分无论如何都不打印),但这不起作用。

以下是代码:

def wordlocator(word):
    yourWord = word
    print("You have chosen the following word: " +yourWord)
    aString = input("What string would you like to search for the given word?")
    aString = aString.lower()
    aString = aString.split()
    b = [(i, j) for i, j in enumerate(aString)]
    c = [(i, x) for i, x in b if x == yourWord]
    return c

我正在寻找的输出是,如果有人......

wordlocator("word")
"please input a string generic message" "that is a word"
"4, word"

目前可行,但它会打印"3, word"。如果字符串为"that is a word and this is also a word",那么它会忽略"word"的进一步出现。 编辑:现在工作,使用更简单的代码。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

试试这个:

def wordlocator(word):
    yourWord = word
    print("You have chosen the following word: " +yourWord)
    aString = raw_input("What string would you like to search for the given word?")
    aString = aString.lower()
    aString = aString.split()
    b = [(i+1, j) for i, j in enumerate(aString) if j == yourWord.lower()]

    return b

print wordlocator('word')

请注意,列表推导可以仅根据您要查找的匹配进行过滤。其实我只是改了它

我明白了:

What string would you like to search for the given word?This word is not that word is it?
[(2, 'word'), (6, 'word')]

请注意,如果重要的话,索引会减1,在理解

中将x添加到x

新测试: 您选择了以下单词:word 你想用什么字符串搜索给定的单词?单词是单词 [(1,'word'),(4,'word')]

相关问题