文本数据是数据中最非结构化的形式之一,包含各种各样的噪声。为了使文本数据便于分析,需要进行文本预处理。文本预处理的主要目的是清除噪声并使其标准化,以便后续分析。
文本预处理主要包含三个步骤:移除噪声、词汇规范化和对象标准化。
文本中的噪声包括停用词(如“is”、“a”、“the”等)、URL、社交媒体实体(如提及和标签)、标点符号以及特定行业的词汇。移除噪声的方法包括使用噪声词典和正则表达式。
以下是Python代码示例:
```python
noise_list = ["is", "a", "the"]
def removenoise(inputtext): words = inputtext.split() noisefreewords = [word for word in words if word not in noiselist] noisefreetext = " ".join(noisefreewords) return noisefreetext
remove_noise("this is a sample text") ```
另一种方法是使用正则表达式:
```python
import re
def removeregex(inputtext, regexpattern): urls = re.finditer(regexpattern, inputtext) for i in urls: inputtext = re.sub(i.group().strip(), '', inputtext) return inputtext
regexpattern = "#[A-Za-z0-9w]*" removeregex("remove this #hashtag from analytics vidhya", regex_pattern) ```
词汇规范化是将同一个词的不同形态统一为一种规范形式,这有助于减少数据维度。常见的词汇规范化方法包括词干提取和词形还原。
以下是Python代码示例:
```python from nltk.stem.wordnet import WordNetLemmatizer lem = WordNetLemmatizer()
from nltk.stem.porter import PorterStemmer stem = PorterStemmer()
word = "multiplying"
lem.lemmatize(word, "v") stem.stem(word) ```
对象标准化是指将文本中的非标准词汇或短语替换为标准形式。这可以通过使用词典和正则表达式来实现。
以下是Python代码示例:
```python lookup_dict = {'rt':'Retweet', 'dm':'direct message', "awsm" : "awesome", "luv" :"love"}
def lookupwords(inputtext): words = inputtext.split() newwords = [] for word in words: if word.lower() in lookupdict: word = lookupdict[word.lower()] newwords.append(word) newtext = " ".join(newwords) return newtext
lookup_words("RT this is a retweeted tweet by Shivam Bansal") ```
预处理后的文本数据需要进一步转化为特征,以便进行机器学习分析。常见的特征工程技术包括句法分析、实体提取、统计特征和词嵌入。
句法分析包括依存语法和词性标注。依存语法可以表示词语间的依存关系,词性标注则将每个词与词性关联起来。
以下是Python代码示例:
```python from nltk import wordtokenize, postag
text = "I am learning Natural Language Processing on Analytics Vidhya"
tokens = wordtokenize(text) postags = postag(tokens) print(postags) ```
实体提取包括命名实体识别和主题建模。命名实体识别可以识别出人名、公司名和地位等实体,主题建模则可以从文本中提取出隐藏的主题。
以下是Python代码示例:
```python doc1 = "Sugar is bad to consume. My sister likes to have sugar, but not my father." doc2 = "My father spends a lot of time driving my sister around to dance practice." doc3 = "Doctors suggest that driving may cause increased stress and blood pressure."
doccomplete = [doc1, doc2, doc3] docclean = [doc.split() for doc in doc_complete]
import gensim from gensim import corpora
dictionary = corpora.Dictionary(docclean) doctermmatrix = [dictionary.doc2bow(doc) for doc in docclean]
Lda = gensim.models.ldamodel.LdaModel ldamodel = Lda(doctermmatrix, num_topics=3, id2word=dictionary, passes=50)
print(ldamodel.print_topics()) ```
统计特征包括术语频率-逆文献频率(TF-IDF)。TF-IDF是一种常用的文本向量化方法,用于衡量词在文档中的重要性。
以下是Python代码示例:
```python from sklearn.feature_extraction.text import TfidfVectorizer
obj = TfidfVectorizer() corpus = ['This is sample document.', 'another random document.', 'third sample document text'] X = obj.fit_transform(corpus) print(X) ```
词嵌入是一种将词表示为向量的方法,常用于深度学习领域。Word2Vec和GloVe是两种流行的词嵌入工具包。
以下是Python代码示例:
```python from gensim.models import Word2Vec
sentences = [['data', 'science'], ['vidhya', 'science', 'data', 'analytics'], ['machine', 'learning'], ['deep', 'learning']]
model = Word2Vec(sentences, min_count=1) print(model.similarity('data', 'science')) print(model['learning']) ```
通过以上步骤,我们可以有效地清理和标准化文本数据,并将其转化为适合机器学习分析的特征。