nlp 中文資料預處理

2021-10-01 04:26:47 字數 2167 閱讀 1219

資料載入(預設csv格式)

import pandas as pd

datas = pd.read_csv("./test.csv", header=0, index_col=0) # dataframe

n_datas = data.to_numpy() # ndarray 轉成numpy更好處理(個人喜好)

去除空行
def delete_blank_lines(sentences):

return [s for s in sentences if s.split()]

no_line_datas = delete_blank_lines(n_datas)

去除數字
digit_re = re.compile(r'\d+')

no_digit_datas = digit_re.sub('', no_line_datas)

def delete_digit(sentences):

return [digit_re.sub('', s) for s in sentences]

判斷句子形式(簡單句或者複雜句)
stops = ['。', '.', '?', '?', '!', '!']  # 中英文句末字元

def is_sample_sentence(sentence):

count = 0

for word in sentence:

if word in stops:

count += 1

if count > 1:

return false

return true

去除中英文標點
from string import punctuation

import re

punc = punctuation + u'.,;《》?!「」『』@#¥%…&×()——+【】{};;●,。&~、|\s::'

def delete_punc(sentences):

return [re.sub(r"[{}]+".format(punc), '', s) for s in a]

去除英文(僅留漢字)
english_re = re.compile(r'[a-za-z]+')

def delete_e_word(sentences):

return [english_re.sub('', s) for s in sentences]

去除亂碼和特殊符號

使用正規表示式去除相關無用符號和亂碼

# 該操作可以去掉所有的符號,標點和英文,由於前期可能需要標點進一步判斷句子是否為簡單句,所以該操作可以放到最後使用。

special_symbol_re = re.compile(r'[^\w\s\u4e00-\u9fa5]+')

def delete_special_symbol(sentences):

return [special_symbol_re.sub('', s) for s in sentences]

中文分詞
# 使用jieba

def seg_sentences(sentences):

cut_words = map(lambda s: list(jieba.cut(s)), sentences)

return list(cut_words)

# 使用pyltp分詞

def seg_sentences(sentences):

segmentor = segmentor()

segmentor.load('./cws.model') # 載入分詞模型引數

seg_sents = [list(segmentor.segment(sent)) for sent in sentences]

segmentor.release()

return seg_sents

去除停用詞

stopwords =

def delete_stop_word(sentences):

return [[word for word in s if word not in stopwords] for s in sentences]

references

NLP 中文文字預處理

jieba是乙個專門處理中文分詞的分詞庫,但其實功能比單純的分詞強大許多。中文不同於英文可以通過空格分開每個有意義的詞,對於中文需要乙個工具將完整的文字分割成更細緻的詞語,類似於英文分詞中使用的nltk工具,中文中需要使用jieba。pip install jieba 4.詞性標註 5.tokeni...

NLP 英文資料預處理

目錄 理論 文字特徵提取 詞袋模型 tf idf模型 高階詞向量模型 部分 gensim doc2bow lda gensim tfidf lda 結果對比 主流 谷歌的word2vec演算法,它是乙個基於神經網路的實現,使用cbow continuous bags of words 和skip g...

NLP筆記1 中文分詞(資料預處理篇)

如何實現準確並且迅速的中文分詞一直是自然語言處理領域研究中的基礎。這三類分詞技術代表了當前中文分詞的發展方向,它們有著各自的優缺點。基於字串匹配的分詞是通過構建乙個固定的詞表,對照這個詞表,對輸入的問句進行字串擷取和字串匹配。主要原理是將問句從頭開始不斷切割成若干個子字串,當所有的子字串都能夠與詞表...