【问题标题】:How to find the position of a word in a string / list?如何在字符串/列表中查找单词的位置?
【发布时间】:2016-06-28 15:28:57
【问题描述】:

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

我目前的代码只是识别单词的第一次出现,没有进一步的。如果单词是字符串中的第一个单词,它也不会识别该单词,返回一个空列表。它还会说出单词的实际位置 - 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" 的进一步出现。 编辑:现在可以工作了,使用了一段更简单的代码。感谢大家的帮助!

【问题讨论】:

  • "第一个单词被计为零" - 是的,Python 的索引是从 0 开始的。不过,您可以选择从另一个值开始 enumerate - 请参阅其文档。
  • Python(我认为我使用过的所有语言)索引为零。如果您需要实数位置,只需添加 1。至于仅获得第一次使用 - 您可以根据以下答案修复列表理解或查看“yield” - 检查此问题here
  • @Lost 如果我没记错的话,Cobol 对数组使用 1 索引。操作,我无法重现您只找到一次出现的问题,您的代码对我来说很好。但也许问题在于用户输入标点符号:'word' != 'word.' != 'word,'

标签: python string list position word


【解决方案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')]

请注意,如果重要,索引会减一,请在推导式中将 x 加一

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

【讨论】:

  • 您好,谢谢您的回复!我走了有点抱歉这么晚才感谢你! :) 再次感谢!! :)
  • @chunkydumpling 你可以检查你是否喜欢答案。没问题。乐于助人
  • 嗨,我刚刚试过这个,但它仍然不适用于第一次出现的单词?你觉得我应该怎么做?例如做 "wordlocator("word") \n what string... "word this is" \n "[ ]"
  • 它对我有用。您使用的是 python 2.7 还是 3.?我在上面添加了我的结果
  • 我使用的是 3.5.2,虽然在学校我们使用的是 3.3.3
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
相关资源
最近更新 更多