我正在尝试使用Regex来提取标题中的短语和句子中出现的单词。
到目前为止的努力。
(?:[A-Z][a-z]+\s?)+
这个Regex代码应用于下面的示例句子时 可以找到那些粗体字。但我需要忽略像This和Whether这样的词(句子开头)。
样例句。
This 是一个 例句 以检查 实际价值 本守则的。无论 行不行 不 取决于结果。
期待。
这是一个 例句 以检查 实际价值 的这段代码。无论它是否有效 不 取决于结果。
有用的代码。
import regex as re
text='This is a Sample Sentence to check the Real Value of this code. Whether it works or Not depends upon the result. A State Of The Art Technology is needed to do this work.'
rex=r'(?<!^|[.!?]\ )\b[A-Z][a-z]+(?:\ [A-Z][a-z]+)*\b'
matches = re.finditer(rex,text)
results = [match[0] for match in matches]
print(results)
结果:
['Sample Sentence', 'Real Value', 'Not', 'State Of The Art Technology']
如果您的句子总是单倍行距,您可以使用正向的lookbehind查找字母和空格,以找到标题格式的表达式的开始。
(?<=[a-z,] )(?:[A-Z][a-z]+(?![a-z]).)+
这个regex允许表达式以标点符号结束,而不是仅仅以空格结束(例如. the Final Result.
).