Python NLP:如何使用nltk从文本文件提取中间项为形容词的三元组
基于NLTK提取中间项为形容词的三元组实现方案
需求说明
从文本文件中识别「限定词/冠词 + 形容词 + 名词」结构的三元组,中间项固定为形容词。
示例输入文本:A red ball was with the good boy.
预期输出:
('A','red','ball'), ('the','good','boy')
前置准备
- 安装nltk库
pip install nltk
- 下载nltk所需的分词和词性标注数据包
import nltk nltk.download('punkt') nltk.download('averaged_perceptron_tagger')
实现逻辑
- 读取目标文本文件内容
- 对文本进行分词处理
- 对分词结果进行词性标注
- 用长度为3的滑动窗口遍历标注结果,匹配以下规则:
- 第一个词词性为限定词(DT,对应冠词、指示代词等)
- 中间词词性为形容词(通用形容词对应
JJ,如果需要包含比较级、最高级可追加JJR、JJS) - 第三个词词性为名词(通用名词对应
NN,如果需要包含复数名词、专有名词可追加NNS、NNP、NNPS)
- 收集所有匹配的三元组,按要求格式输出
完整实现代码
import nltk from nltk.tokenize import word_tokenize from nltk import pos_tag def extract_adj_triples(file_path): # 读取文本文件 with open(file_path, 'r', encoding='utf-8') as f: text = f.read() # 分词+词性标注 tokens = word_tokenize(text) tagged = pos_tag(tokens) triples = [] # 滑动窗口遍历 for i in range(len(tagged) - 2): w1, pos1 = tagged[i] w2, pos2 = tagged[i+1] w3, pos3 = tagged[i+2] # 匹配规则,可根据需求调整词性范围 if pos1 == 'DT' and pos2 == 'JJ' and pos3 == 'NN': triples.append((w1, w2, w3)) # 格式化输出 output = ', '.join([str(t) for t in triples]) return output # 调用示例,替换为你的文本文件路径 if __name__ == "__main__": result = extract_adj_triples("test.txt") print(result)
测试效果
将示例文本存入test.txt文件,运行代码后输出如下:
('A', 'red', 'ball'), ('the', 'good', 'boy')
自定义调整说明
- 如需匹配形容词比较级/最高级,可将
pos2 == 'JJ'修改为pos2 in ['JJ', 'JJR', 'JJS'] - 如需匹配复数名词、专有名词,可将
pos3 == 'NN'修改为pos3 in ['NN', 'NNS', 'NNP', 'NNPS']
内容的提问来源于stack exchange,提问作者Sky_7
相关产品推荐
相关产品推荐

