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

2024-09-30 20:17:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个函数,用户输入一个单词,然后输入一个字符串,这个函数识别所有出现的单词以及该单词在字符串中的位置(尽管它实际上在中途被转换成了一个列表)。在

我目前的代码只识别第一次出现的单词,没有进一步的。如果单词是字符串中的第一个单词,它也不会识别该单词,返回一个空列表。它还将显示单词的实际位置-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

我要找的结果是如果有人。。。在

^{pr2}$

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


Tags: the函数字符串代码in列表forif
1条回答
网友
1楼 · 发布于 2024-09-30 20:17:51

试试这个:

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

请注意,列表理解可以根据您要查找的匹配项进行筛选。实际上我刚换了

我明白了:

^{pr2}$

请注意,如果重要的话,索引将减少1,在理解中加一到x

新的测试: 您选择了以下单词:word 要搜索给定单词的字符串?一言为定 [(1,'字',(4,'字')]

相关问题 更多 >