You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python定位句子中指定单词的位置?

实现Python查找句子中单词位置的方法

嘿,这个需求很清晰,咱们来一步步实现这个locate_word函数,完美匹配你给出的例子!

核心思路

要解决这个问题,关键在于两点:

  • 正确分割句子中的单词,同时处理单词附带的标点(比如例子里的world.)
  • 从1开始计数,找到目标单词的位置

完整实现代码

import string

def locate_word(word, sentence):
    # 按空格分割句子,自动处理多空格情况
    candidate_words = sentence.split()
    # 遍历候选单词,从1开始计数
    for position, candidate in enumerate(candidate_words, start=1):
        # 去除单词前后的所有标点符号,避免标点干扰匹配
        cleaned_candidate = candidate.strip(string.punctuation)
        # 精准匹配目标单词
        if cleaned_candidate == word:
            return position
    # 如果未找到目标单词,返回None(也可以根据需求改成0或其他值)
    return None

测试你的例子

把你的测试用例代入,看看结果:

sentence = "It's a beautiful world."
word = "world"
print(locate_word(word, sentence))  # 输出:4,完全符合预期!

额外优化说明

如果需要处理更多场景,可以做这些调整:

  • 忽略大小写匹配:把判断条件改成cleaned_candidate.lower() == word.lower(),这样World也能匹配到world
  • 返回所有匹配位置:如果单词在句子中出现多次,可以收集所有符合条件的位置,比如:
    def locate_word_all(word, sentence):
        candidate_words = sentence.split()
        positions = []
        for pos, candidate in enumerate(candidate_words, start=1):
            cleaned = candidate.strip(string.punctuation)
            if cleaned == word:
                positions.append(pos)
        return positions or None
    
  • 处理特殊格式单词:比如带连字符的state-of-the-art,如果你的目标单词是state-of-the-art,当前逻辑也能正常匹配,因为strip只会去除首尾标点,不会影响中间的符号。

内容的提问来源于stack exchange,提问作者yishairasowsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:13:42