Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以特定方式修剪字符串_Python - Fatal编程技术网

Python 如何以特定方式修剪字符串

Python 如何以特定方式修剪字符串,python,Python,假设我有这样一句话: 这种鸟在夜间飞行,翼展很大 我的目标是拆分字符串,以便得到以下结果: 它有一个很大的翅膀 我尝试过使用split(),但是,我的努力没有成功。如何将字符串拆分为几段,并删除字符串的开头部分和结尾部分?我想这是实现您所需的最佳方法: import re text = 'The bird flies at night and has a very large wing span.' l = re.split(r'.+?(?=and)|(?<=wing).+?', text

假设我有这样一句话:

这种鸟在夜间飞行,翼展很大

我的目标是拆分字符串,以便得到以下结果:

它有一个很大的翅膀


我尝试过使用
split()
,但是,我的努力没有成功。如何将字符串拆分为几段,并删除字符串的开头部分和结尾部分?

我想这是实现您所需的最佳方法:

import re
text = 'The bird flies at night and has a very large wing span.'
l = re.split(r'.+?(?=and)|(?<=wing).+?', text)[1]
s = "The bird flies at night and has a very large wing span."
and_position = s.find("and") # return the first index of "and" in the string
wing_position = s.find("wing") # similar to the above
result = s[and_position:wing_position+4] # this is called python's slice

如果您不熟悉python slice,请阅读。

上的更多内容,直到您解释了更多应该遵循的逻辑,任何人都能做的最多的事情就是提供各种方法将输入字符串转换为输出字符串(其中有许多)。您真的应该使用专用的自然语言处理器。例如。@TigerhawkT3我的逻辑是修剪“and”前面的给定字符串和“large”后面的字符串。此解决方案的最佳方法是什么?您是否专门寻找以字符
开头并一直持续到字符
后的一个(以空格分隔的)字的子字符串?你的目标还不清楚。也许你可以编辑你的问题,将你提到的“努力”包括在内。下次投票否决我时,请留下评论。我不知道我的代码出了什么问题,不是一个失败的选民。我猜这是由于OP的评论,我的逻辑是删减“and”前面的给定字符串,以及“large”后面的单词。解决这个问题的最佳方法是什么?您正在使用硬编码indexes@Moinuddin我明白了。ths
s = "The bird flies at night and has a very large wing span."
and_position = s.find("and") # return the first index of "and" in the string
wing_position = s.find("wing") # similar to the above
result = s[and_position:wing_position+4] # this is called python's slice