要在 Python 中提取对方的关键语句,需要先定义关键语句的标准。比如说,你可以定义关键语句为句子的首字母大写,或者包含某些特定的关键字。
一种方法是使用正则表达式来匹配关键语句。你可以使用 Python 的 re
模块来使用正则表达式。例如,下面的代码使用正则表达式来查找所有以大写字母开头的句子:
import re
text = "The quick brown fox jumps over the lazy dog. Hello World!"
pattern = r'[A-Z][^.!?]*[.!?]'
key_sentences = re.findall(pattern, text)
print(key_sentences) # ['The quick brown fox jumps over the lazy dog.', 'Hello World!']
另一种方法是使用 Python 的 nltk
库,该库提供了自然语言处理的功能。你可以使用 nltk
库的 sent_tokenize
函数来分割文本为句子,然后遍历每个句子并检查是否符合你定义的关键语句的标准。例如,下面的代码使用 nltk
库来查找所有以大写字母开头的句子:
import nltktext = "The quick brown fox jumps over the lazy dog. Hello World!"
key_sentences = []
for sentence in nltk.sent_tokenize(text):
if sentence[0].isupper():
key_sentences.append(sentence)
print(key_sentences) # ['The quick brown fox jumps over the lazy dog.', 'Hello World!']
注意,上面两个例子中使用的正则表达式和判断条件都是简单的例子,实际情