截断在 Python 中该字符串中找到的单词周围的字符串

Truncate a string around a word found in that string in Python

我想在字符串中找到一个词,然后截断该词周围的 python 字符串。

示例: str1 = "我想尝试 select 这个世界上的一些特定事物。你能帮我做吗"

现在我想在字符串中找到特定的单词,然后截断字符串的开头和结尾,以便在该单词周围说出 15 个字符。

所以答案应该是这样的: "nd select 一些具体的东西"

这基本上就是“具体”左右15个字符。

提前致谢

如何使用find()函数,returns要查找的单词首字母的索引,否则抛出异常:

x = "I want to try and select some specific thing in this world. Can you please help me do that"
word = "specific"
limit = 15

try:
    index = x.find(word)
    output = x[max(0, index-limit):min(len(x), index+limit+len(word))]
    print(output)
except:
    print("Word not found")

哦,x[:] 是一种 拼接 字符串的方法,这是 python 调用 子字符串的方法

max 和 min 函数防止子串的限制超出原始输入的长度