在Python中使用正則表達式提取文章中的形容詞需要結合語言特性處理。以下是分步解決方案:
- 英文場景解決方案(推薦使用專業NLP庫):
import re
import nltk
nltk.download('averaged_perceptron_tagger') # 首次使用需要下載text = "The quick brown fox jumps over the lazy dog. Interesting discoveries await us."# 方法1:正則表達式基礎匹配(準確性有限)
# 匹配常見形容詞后綴模式
adj_pattern = r'\b\w+(?:able|ible|al|ful|ic|ive|less|ous|y|ed|ing)\b(?!\s*[\w-]+)'
adjectives = re.findall(adj_pattern, text, flags=re.IGNORECASE)# 方法2:使用nltk詞性標注(推薦)
words = nltk.word_tokenize(text)
tagged = nltk.pos_tag(words)
proper_adjectives = [word for word, pos in tagged if pos in ['JJ', 'JJR', 'JJS']]print("正則匹配結果:", adjectives)
print("NLP解析結果:", proper_adjectives)
- 中文場景解決方案(需要分詞和詞性標注):
import jieba
import jieba.posseg as psegtext = "美麗的花兒在陽光下綻放,散發著迷人的芬芳。"# 使用結巴分詞進行詞性標注
words = pseg.cut(text)
adjectives = [word for word, flag in words if flag.startswith('a')] # a開頭表示形容詞print("中文形容詞提取結果:", adjectives)
關鍵說明:
-
正則表達式的局限性:
- 無法準確處理不規則形容詞(good/better/best)
- 可能誤判名詞的形容詞形式(如"apple juice"中的"apple")
- 無法識別復合形容詞(如"state-of-the-art")
-
推薦方案:
- 英文:使用spaCy(更精準的詞性標注)
import spacy nlp = spacy.load('en_core_web_sm') doc = nlp("The quick brown fox...") adjectives = [token.text for token in doc if token.pos_ == 'ADJ']
- 中文:推薦使用LTP或HanLP等專業中文NLP工具
-
增強正則方案(英文):
# 匹配標準形容詞模式(包含比較級/最高級)
adj_pattern = r'''\b # 單詞邊界(?: # 非捕獲組(?:[A-Za-z]+) # 基礎形容詞(?: # 可選后綴(?:er|est)? # 比較級/最高級|(?:ly) # 副詞形式(需額外過濾)|(?:ed|ing) # 分詞形式(需額外過濾)))\b # 單詞邊界
'''
adjectives = re.findall(adj_pattern, text, re.VERBOSE | re.IGNORECASE)
建議根據實際需求選擇方案:
- 快速簡單需求:使用基礎正則表達式
- 準確分析需求:使用NLP工具庫(推薦spaCy/NLTK)
- 中文處理:必須使用中文分詞工具(如jieba、LTP)
注意:純正則方案無法達到專業NLP工具90%以上的準確率,在正式文本分析中建議優先使用成熟的NLP庫。