[英]How do I remove the substrings started with capital letters in a Python string?
我有这个字符串,它是标题和常规句子之间的混合(两者之间没有分隔符)。
text = "Read more: Indonesia to Get Moderna Vaccines Before the pandemic began, a lot of people were...."
标题实际上以Vaccines
一词结尾, Before the pandemic
是另一个与标题完全分开的句子。
如何删除 substring 直到单词疫苗? 我的想法是从“阅读更多:”一词中删除所有单词,然后删除以大写字母开头的所有单词,直到一个单词之前( before
)。 但是我不知道如果它遇到不需要在标题中大写的连词或介词,比如单词the
.
I know there is a function title()
to convert a string into a title format in Python, but is there any function that can detect if a substring is a title?
我使用正则表达式尝试了以下操作。
import re
text = "Read more: Indonesia to Get Moderna Vaccines Before the pandemic began, a lot of people were...."
res = re.sub(r"\s*[A-Z]\s*", " ", text)
res
但它只是删除了所有以大写字母开头的单词。
您可以通过匹配一系列大写单词和标题中可以不大写的单词来匹配标题。
^(?:Read\s+more\s*:)?\s*(?:(?:[A-Z]\S*|the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)\s+)*(?=[A-Z])
请参阅正则表达式演示。
详情:
^
- 字符串的开头(?:Read\s+more\s*:)?
- 一个可选的非捕获组匹配Read
、一个或多个空格、 more
、零个或多个空格和一个:
\s*
- 零个或多个空格(?:(?:[AZ]\S*|the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)\s+)*
- 零个或多个序列
(?:[AZ]\S*|the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)
- 一个大写的单词,可以包含任何非空白字符或在英文标题中可以保持非大写的单词之一\s+
- 一个或多个空格(?=[AZ])
- 后跟一个大写字母。注意:您提到您的语言不是英语,所以
^(?:Read\s+more\s*:)?\s*(?:(?:[AZ]\S*|the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of
[AZ]
替换为\p{Lu}
以匹配任何 Unicode 大写字母,并将\S*
替换为\p{L}*
以匹配任何零个或多个 Unicode 字母,但请确保您使用 PyPi 正则表达式库因为 Python 内置re
不支持 Unicode 类别类。为什么不直接使用切片?
title = text[:44]
print(title)
阅读更多:印度尼西亚将获得 Moderna 疫苗
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.