gpt4 book ai didi

python - 获取文本中子字符串前后单词的有效方法(python)

转载 作者:太空狗 更新时间:2023-10-29 21:45:59 26 4
gpt4 key购买 nike

我正在使用正则表达式查找文本正文中出现的字符串模式。一旦发现字符串模式出现,我也想在字符串前后获取 x 个单词(x 可以小到 4,但如果仍然有效的话,最好是 ~10)。

我目前正在使用正则表达式查找所有实例,但偶尔会挂起。有没有更有效的方法来解决这个问题?

这是我目前的解决方案:

sub = r'(\w*)\W*(\w*)\W*(\w*)\W*(\w*)\W*(%s)\W*(\w*)\W*(\w*)\W*(\w*)\W*(\w*)' % result_string #refind string and get surrounding += 4 words
surrounding_text = re.findall(sub, text)
for found_text in surrounding_text:
result_found.append(" ".join(map(str,found_text)))

最佳答案

我不确定这是否是您要找的:

>>> text = "Hello, world. Regular expressions are not always the answer."
>>> words = text.partition("Regular expressions")
>>> words
('Hello, world. ', 'Regular expressions', ' are not always the answer.')
>>> words_before = words[0]
>>> words_before
'Hello, world. '
>>> separator = words[1]
>>> separator
'Regular expressions'
>>> words_after = words[2]
>>> words_after
' are not always the answer.'

基本上,str.partition() 将字符串拆分为 3 元素元组。在此示例中,第一个元素是特定“分隔符”之前的所有单词,第二个元素是分隔符,第三个元素是分隔符之后的所有单词。

关于python - 获取文本中子字符串前后单词的有效方法(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31897436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com