文本清洗

Python 中的 NLP 特征工程

Rounak Banik

Data Scientist

文本清洗技术

  • 多余空格与转义序列
  • 标点
  • 特殊字符(数字、表情等)
  • 停用词
Python 中的 NLP 特征工程

isalpha()

"Dog".isalpha()
True
"3dogs".isalpha()
False
"12347".isalpha()
False
"!".isalpha()
False
"❤".isalpha()
False
Python 中的 NLP 特征工程

注意事项

  • 缩写:U.S.AU.K
  • 专有名词:word2vecxto10x
  • 更复杂的情况可用自定义函数(正则)处理。
Python 中的 NLP 特征工程

移除非字母字符

string = """
OMG!!!! This is like    the best thing ever \t\n. 
Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤
"""

import spacy # Generate list of tokens nlp = spacy.load('en_core_web_sm') doc = nlp(string) lemmas = [token.lemma_ for token in doc]
Python 中的 NLP 特征工程

移除非字母字符

...
...
# Remove tokens that are not alphabetic
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() or lemma == '-PRON-']

# Print string after text cleaning print(' '.join(a_lemmas))
'omg this be like the good thing ever wow such an amazing song -PRON- be hooked top definitely'
Python 中的 NLP 特征工程

停用词

  • 极高频词
  • 如:冠词、be 动词、代词等
Python 中的 NLP 特征工程

用 spaCy 移除停用词

# Get list of stopwords
stopwords = spacy.lang.en.stop_words.STOP_WORDS

string = """ OMG!!!! This is like the best thing ever \t\n. Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤ """
Python 中的 NLP 特征工程

用 spaCy 移除停用词

...
...
# Remove stopwords and non-alphabetic tokens
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() and lemma not in stopwords]
# Print string after text cleaning
print(' '.join(a_lemmas))
'omg like good thing wow amazing song hooked definitely'
Python 中的 NLP 特征工程

其他文本预处理技术

  • 去除 HTML/XML 标签
  • 替换重音字符(如 é)
  • 拼写纠正
Python 中的 NLP 特征工程

注意事项

仅使用与您的应用相关的预处理技术。

Python 中的 NLP 特征工程

Vamos praticar!

Python 中的 NLP 特征工程

Preparing Video For Download...