【自然语言处理(一)】相关基础技能
1.python字符串相關操作
s1 = " hello "
s2 = " world! "
#去除字符串左右兩邊的空格
s1 = s1.strip()
s2 = s2.strip()
#拼接字符串
s = s1+s2
#查找字符或子串
s_index = s.index('hello')
#字符串大小寫轉換
s3 = "ABC"
s4 = "abc"
s3_lower = s3.lower()
s4_upper = s4.upper()
#翻轉字符串
s_reverse = s[::-1]
#查找字符串
s_find = s.find("hello")
#分割字符串
s5 = "a,b,c,d,e"
s5_split = s5.split(",")
import re
from collections import Counter
#獲取字符串中出現最多次數的字符
def count_char(str):
str = str.lower()
res = re.findall("[a-z]",str)
count = Counter(res)
return [k for k,v in count.items() if v==max(list(count.values()))]
2.正則表達式(網上很多教程,關鍵還是理解每一個代表什么意思,還要多寫,其實沒什么大不了,這里就不寫了)就只寫寫python中是怎么用的
import re
#compile傳入兩個參數,第一個是pattern,第二個是flag(這個根據實際情況使用)
pattern = re.compile(r"(w+) (w+)(?P<sign>.*)")
match = pattern.match("hello gongoubo!")
if match:
#匹配時使用的文本
print(match.string)
#匹配時使用的pattern對象
print(match.re)
#開始搜索的索引
print(match.pos)
#結束搜索的索引
print(match.endpos)
#最后一個分組的索引
print(match.lastindex)
#最后一個分組別名
print(match.lastgroup)
print(match.group(1,2))
print(match.groups())
print(match.groupdict())
print(match.start(2))
print(match.end(2))
print(match.span(2))
print(match.expand(r'2 13'))
(1)進行制定的切分
import re
pattern = re.compile(r"d+")
print(pattern.split("one1two2three3four4"))
(2)返回全部匹配的字符串
import re
pattern = re.compile(r"d+")
print(pattern.findall("one1two2three3four4"))
(3)替換掉符合某種模式的字符串
import re pattern1 = re.compile(r"(w+) (w+)") pattern2 =re.compile(r' ') s1="say i hellogongoubo" s2="ni hao a " print(pattern1.sub(r'2 1',s1)) print(pattern2.sub(r'!',s2))
3.jieba中文處理
import jieba
#全模式:把句子中所有的可以成詞的詞語都掃描出來,速度非常快,但不能解決歧義;
seg_list= jieba.cut("我愛學習自然語言處理",cut_all=True,HMM=False)
print("Full Mode:"+"/".join(seg_list))
#精確模式,如不指定,默認是這個模式,適合文本分析;
seg_list= jieba.cut("我愛學習自然語言處理",cut_all=False,HMM=False)
print("Full Mode:"+"/".join(seg_list))
#搜索引擎模式,在精確模式的基礎上,對長詞再次切分,提高召回率
seg_list=jieba.cut_for_search("小明碩士畢業于中國科學技術學院計算所,后在哈佛大學深造")
print("Full Mode:"+"/".join(seg_list))
#lcut,lcut_for_search返回的是列表
seg_list= jieba.lcut("我愛學習自然語言處理",cut_all=True)
print(seg_list)
(1)添加用戶自定義詞典:
1)可以利用jieba.load_userdict(file_name)加載用戶字典;
2)少量詞匯可以手動添加:
add_word(word,freq=None,lag=None)和del_word(word)在程序中動態修改字典,這時HMM要設置為False
用suggest_freq(segment,tune=True)可調節單個詞語的詞頻,使其能(或不能)被分出來
import jieba
seg_list= jieba.cut("如果放在舊字典中將出錯",cut_all=False,HMM=False)
print(','.join(seg_list))
jieba.suggest_freq(("中","將"),tune=True)
seg_list= jieba.cut("如果放在舊字典中將出錯",cut_all=False,HMM=False)
print(','.join(seg_list))
會發現"中將"被拆為"中"和"將"了。
(2)基于TF-IDF算法的關鍵詞提取
jieba.analyse.extract_tags(sentense,topK=20,withWeight=False,allowPOS=())
sentense:待提取的文本
topK:返回權重較大的前多少個關鍵詞
withWeight:是否一并返回權重值,默認為False
allowPOS:僅保留指定詞性的詞,默認為空
from jieba import analyse
text = "Python是一種跨平臺的計算機程序設計語言。是一種面向對象的動態類型語言,"
"最初被設計用于編寫自動化腳本(shell),隨著版本的不斷更新和語言新功能的添加,"
"越來越多被用于獨立的、大型項目的開發。"
print(" ".join(analyse.extract_tags(text)))
注意:關鍵詞提取所使用的的逆文檔頻率(IDF)文本語料庫可以切換成自定義語料庫的路徑:
jieba.analyse.set_idf_path(file_name)
關鍵詞提取所使用的停止詞文本語料庫也可以切換成自定義語料庫的路徑:
jieba.analyse.set_stop_words(file_name)
(2)基于TextRank算法的關鍵詞提取
jieba.analyse.textrank(sentense,topK=20,withWeight=False,allowPOS=('ns','n','vn','v'))
基本思想:
將待提取的關鍵詞進行文本分詞;
以固定窗口大?。J為5,通過span屬性調整),詞之間的共現關系,構建圖;
計算圖中節點的PageRank;(無向帶權圖)
from jieba import analyse
text = "Python是一種跨平臺的計算機程序設計語言。是一種面向對象的動態類型語言,"
"最初被設計用于編寫自動化腳本(shell),隨著版本的不斷更新和語言新功能的添加,"
"越來越多被用于獨立的、大型項目的開發。"
print(" ".join(analyse.textrank(text)))
(3)詞性標注
jieba.posseg.POSTTokenizer(tokenizer=None)新建自定義分詞器,tokenizer參數可指定內部使用的jieba.Tokenizer分詞器。jieba.prosseg.dt默認詞性標注分詞器;
標注句子分詞后每個詞的詞性,采用和ictclas兼容的標記法;
from jieba import posseg
text = "我愛自然語言處理"
words = posseg.cut(text)
for word, flag in words:
print("{},{}".format(word,flag))
(4)并行分詞
jieba.enable_parallel()
import jieba
import time
content=open(u'遮天.txt').read()
def en_parallel(content):
jieba.enable_parallel()
t1=time.time()
words = "/".join(jieba.cut(content))
t2=time.time()
tm_cost=t2-t1
print("并行分詞速度為{} bytes/second".format(len(content)/tm_cost))
def dis_parallel(content):
jieba.disable_parallel()
t1=time.time()
words = "/".join(jieba.cut(content))
t2=time.time()
tm_cost=t2-t1
print("非并行分詞速度為{} bytes/second".format(len(content)/tm_cost))
在windows環境下會報錯,由于沒有Linux系統就不試了
(5)Tokenize:返回詞語在原文的起止位置
import jieba
#默認模式
result=jieba.tokenize(u'自然語言處理有用')
for tk in result:
print("%s start: %d end: %d" % (tk[0],tk[1],tk[2]))
#搜索模式
result=jieba.tokenize(u'自然語言處理有用',mode='search')
for tk in result:
print("%s start: %d end: %d" % (tk[0],tk[1],tk[2]))
總結
以上是生活随笔為你收集整理的【自然语言处理(一)】相关基础技能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CAD绘制图纸的时候怎么延伸直线(如何延
- 下一篇: *结构-04. 通讯录的录入与显示