停用词与标点处理

Python 中的自然语言处理(NLP)

Fouad Trad

Machine Learning Engineer

停用词

  • 频繁出现,但对机器理解上下文贡献有限
  • 在许多 NLP 任务中价值不大
  • 移除后可使模型聚焦重要词

显示多个停用词如 a、an、the、in、of、that、for、by 等的图像。

Python 中的自然语言处理(NLP)

移除停用词

适用于

理解文本主题

显示移动应用中的产品评价的图像

Python 中的自然语言处理(NLP)

移除停用词

适用于

理解文本主题

显示移动应用中的产品评价的图像

不适用于

需要保留文本中每个词的任务

显示将英文(Good morning)翻译成法文(Bonjour)的图像。

Python 中的自然语言处理(NLP)

获取停用词

NLTK 提供多种语言的停用词列表

from nltk.corpus import stopwords
nltk.download('stopwords')

stop_words = stopwords.words('english')
print(stop_words[:10])
['a', 'about', 'above', 'after', 'again', 'against', 'ain', 'all', 'am', 'an']
Python 中的自然语言处理(NLP)

移除停用词

from nltk.tokenize import word_tokenize

text = "This is an example to demonstrate removing stop words."
tokens = word_tokenize(text)
# The .lower() method helps with case sensitivity filtered_tokens = [word for word in tokens if word.lower() not in stop_words]
print(filtered_tokens)
['example', 'demonstrate', 'removing', 'stop', 'words', '.']
Python 中的自然语言处理(NLP)

标点符号

  • 为便于人类阅读而设
  • 在许多 NLP 任务中不含有效信息

显示标点符号和特殊字符的图像。

Python 中的自然语言处理(NLP)

移除标点

适用于

需要在文档中找出常见或重要词的任务

显示需处理的多个文件与文档的图像。

Python 中的自然语言处理(NLP)

移除标点

适用于

需要在文档中找出常见或重要词的任务

显示需处理的多个文件与文档的图像。

不适用于

需保留句子结构以保持清晰度的任务

显示一堆书籍与其生成的摘要文档的图像。

Python 中的自然语言处理(NLP)

访问并移除标点

import string
print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
text = "This is an example to demonstrate removing stop words."
tokens = word_tokenize(text)
filtered_tokens = [word for word in tokens if word.lower() not in stop_words]

clean_tokens = [word for word in filtered_tokens if word not in string.punctuation]
print(clean_tokens)
['example', 'demonstrate', 'removing', 'stop', 'words']
Python 中的自然语言处理(NLP)

Passons à la pratique !

Python 中的自然语言处理(NLP)

Preparing Video For Download...