【问题标题】:How can I find where a word is located in a sentence using python?如何使用python找到一个单词在句子中的位置?
【发布时间】:2019-12-19 21:42:32
【问题描述】:

如何使用python找到一个单词在句子中的位置? 例如句子中的第四个单词。

sentence = "It's a beautiful world."
word = "world"

locate_word(word,sentence) = 4

【问题讨论】:

标签: python string find


【解决方案1】:

您必须指定要如何拆分句子。 我从另一个答案中找到了一个例子。您可以根据需要对其进行修改。

import re

sentence = "It's a beautiful world."
word = "world"

def locate_word(word, sentence):
    # https://stackoverflow.com/a/6181784/12565014
    wordList = re.sub("[^\w]", " ",  sentence).split()
    return wordList.index(word)

locate_word(word,sentence) # output 4

【讨论】:

  • 这是假的,如果这个词是it's
【解决方案2】:

我相信这是一个相当简单且易于阅读的解决方案;

sentence = "It's a beautiful world. Worldwide in the world, for the world"
word = "world"
ax = sentence.split(' ')

import re
for i in ax:
    if len(re.findall('\\world\\b',i)) > 0:
        print(ax.index(i))

输出:

3
7
10

【讨论】:

  • 这不是真的,如果其中一个词是“全球”,它就会失败
  • 已编辑。希望现在没事。
【解决方案3】:

对于上面的例子,它会起作用

import re
sentence = "It's a beautiful world."
word = "world"
lst = sentence.split()
for i in range(0,len(lst)):
    if "." in lst[i]:
        lst[i] = lst[i].replace(".", "")
print(lst.index(word))

【讨论】:

    【解决方案4】:

    拆分句子(默认情况下按空格拆分)然后循环遍历你得到的列表。如果您的单词在列表项中,它将返回它的索引。在此之后,您将 +1 添加到您拥有的索引中,因为列表的计数从 0 开始。

    import string
    def locate_word(word, sentence):
        splitted = sentence.split()
        indexes = []
        for x in splitted:
            if word in x and len(word) == len(x.strip(string.punctuation)):
                indexes.append(splitted.index(x) + 1)
        return print(indexes)
    
    locate_word('worldwide', "It's a worldwide beautiful world. worldwide")
    

    【讨论】:

    • 然后你只需去掉标点符号(在字符串导入的帮助下),并匹配搜索词的长度,它就会给出正确的答案。我根据我的评论编辑了我的代码,还添加了如果世界多次出现在句子中的处理。
    【解决方案5】:

    您可以在空格处拆分句子,然后在列表中查找单词。

    编辑:根据评论,您可能还需要去掉标点符号。

    import string
    
    
    def locate_word(word, sentence):
        sentence = sentence.translate(str.maketrans('', '', string.punctuation))
        ListOfWord = sentence.split(" ")
        return ListOfWord.index(word)
    

    【讨论】:

    • 这是假的,如果这个词是it's
    猜你喜欢
    • 2016-02-08
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多