在某个字符串之后提取一个字符串

2024-06-12 02:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本段落my_text,其中包含如下行

........ licensed in Bangladesh. We are happy to announce ......................
................................................

我想从中提取“孟加拉国”这个词。要决定我是否想要那个词,取决于句子中是否有“licensed in”。你知道吗

当前代码如下:

texts = my_text.split("licensed in")
# extract the word before the first dot (.) from texts[1]

在python中,哪种方法更合适?你知道吗


Tags: thetotextin文本myare句子
2条回答

这是正则表达式的工作:

import re
location = re.search(r"licensed in ([^.]*)", my_text).group(1)

说明:

licensed\ in\   # Match "licensed in "
(               # Match and capture in group 1:
 [^.]*          # Any number of characters except dots.
)               # End of capturing group 1

怎么样

>>> my_text.split('licensed in ')[1].split('.')[0]
'Bangladesh'

相关问题 更多 >