數據清洗
寫代碼前要想好數據該用什么格式輸出,最好在紙上畫出來,然后想如何能實現
更新
read_csv()讀取含中文的csv文件時,
encoding='utf-8'或'gb18030'
,
會遇到有的行無法讀出,增加參數error_bad_lines=False
處理不規范的json文件
import json
mess=[]
with open('謠言.json','r',encoding='utf-8')as f:
lines=f.readlines()
i=0
for line in lines:
print(line)
data=json.loads(line)
mess.append(data)
#i+=1
#if i>200:
#break
print(mess)
NLP短文本處理
強烈推薦KDnuggets系列數據分析、NLP、機器學習文章
(第一天參考文章)[https://blog.csdn.net/eastmount/article/details/50473675]
推薦How to solve 90% of NLP problems: a step-by-step guide
- Tip<1>:Python3下的字符串替換函數str.maketrans(),str.translate()
str.maketrans(intab,outtab)用於創建字符映射的轉換表,intab/outtab都是字符串,前者代表需要轉換的字符,后者是字符要轉換的目標。注意:兩個字符串長度必須相同,一一對應。
translate(table),table(包含256個字符)給出轉換字符串的字符
注意:
Python3中translate還有兩種用法,delete表示要刪除的字符,這里table也得是bytes
bytes.translate(table[, delete])
bytearray.translate(table[, delete])
Python3中的translate函數
>>table=str.maketrans('ab','yz')
>>'abcdefg...xyz'.translate(table)
>>'yzcdefg...xyz'
- Tip<2>:python中提供了一個常量string.punctuation包含所有標點符號列表
這個也不好用,只是英文字符標點
>>string.punctuation
>>'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
總結以上兩個Tip如何刪除停用詞
#去除中文標點符號
intab=',。?:“”‘’;-@'
table=str.maketrans(intab,' '*len(intab))
#可寫作table=str.maketrans('','',intab),上面的寫法會帶有一個空格
text.translate(table)
#去除英文標點
table=str.maketrans('','',string.punctuation)
#建議停用詞不應這樣刪除
#他會把intab中的字符都去掉
NLP之文本清洗
- 將文本分割成句子(再將每個句子分割成單詞),然后將每個句子保存到文件中,每行一個句子。
- 將句子分割成單詞(也叫作標記tokenize),可去標點
- 如果是英文文本,應轉換為小寫
- 去除停用詞
- 如果是英文文本,要提取詞根、詞干
參考:
How to Clean Text for Machine Learning with Python可參考譯文
NLP一些常用詞
Natural Language Processing
Tokenization
Normalization
Stemming
Lemmatization
Corpus
Stop Words
Parts-of-speech(POS) Tagging
Statistical Language Modeling
Bag of Words
n-grams
Regular Expressions
Zipf’s Law
Similarity Measures
Syntactic Analysis
Semantic Analysis
Sentiment Analysis
待讀文章
第二天學習
封裝中文分詞
import jieba
import jieba.posseg as pseg
from jieba.analyse import extract_tags
import re
import pandas as pd
def text_cut(filename,allowPOS=['n','ns','nr','nr2']):
""" :param filename: 文件路徑 :param allowPOS: 選擇需要的詞性 :return: 返回一個DateFrame """
path='D:\\PyCharm 2017.3\\PyProjects\\Rumors\\venv\\Include\\data\\'
jieba.load_userdict(path+'userdict.txt')
f=open(path+filename,'r',encoding='gb18030')
context=f.read()
#把文本按句號等標點分隔開,並刪除換行符
sentence=[i.replace('\n','').strip() for i in re.split('。|!',context)]
#對每一句進行分詞
data={'sentence':[],'posseg':[]}
stop_words=open(path+'stop_words.txt','r',encoding='utf-8').read()
for s in sentence:
#將每個句子分詞
con=[item for item in jieba.lcut(s) if len(item)>1 and item not in stop_words]
data['sentence'].append(' '.join(con))
#提取每句中的所需詞性
seg=pseg.cut(s)
seg_list=['%s'%item for item in seg if item.flag in allowPOS and len(item.word)>1]
data['posseg'].append(' '.join(seg_list))
df_text=pd.DataFrame(data,columns=['sentence','posseg'])
return df_text
待續。。。