简体   繁体   English

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

[英]Truncate a string around a word found in that string in Python

I want to find a word in a string and then truncate the python string around that word.我想在字符串中找到一个单词,然后截断该单词周围的 python 字符串。

Example: str1 = "I want to try and select some specific thing in this world. Can you please help me do that"示例:str1 = "我想尝试在这个世界上选择一些特定的东西。你能帮我做吗"

Now I want to find the word specific in the string and then truncate the string from front and end to say 15 chars around that word.现在我想在字符串中找到特定的单词,然后从前后截断字符串以在该单词周围说出 15 个字符。

So the answer would be something like: "nd select some specific thing in this "所以答案应该是这样的:“在这个中选择一些特定的东西”

This is basically 15 characters left and right from "specific".这基本上是“特定”左右15个字符。

Thanks in advance提前致谢

How about using the find() function, which returns the index of the first letter of the word to be searched, otherwise raises an exception:如何使用find()函数,它返回要搜索的单词的第一个字母的索引,否则引发异常:

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

Oh and the x[:] is a method to splice the string, which is the python way to call a substring哦还有x[:]拼接字符串的方法,是python调用子字符串的方式

The max and min functions prevent the substring's limits from going beyond the length of the original input max 和 min 函数防止子字符串的限制超出原始输入的长度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM