龙空技术网

python文本分析与挖掘(二)-中文分词

不再依然 597

前言:

今天看官们对“python进行分词”大体比较注重,我们都想要了解一些“python进行分词”的相关文章。那么小编在网上汇集了一些对于“python进行分词””的相关资讯,希望小伙伴们能喜欢,同学们一起来了解一下吧!

实现功能:

前一篇文章我介绍了文本分析与挖掘的第一步(具体可参加前一篇文章),构建语料库,这篇文章将在此基础上进行中文分词。

实现代码:

1

import os

2

from warnings import simplefilter

3

simplefilter(action='ignore', category=FutureWarning)

4

import os.path

5

import codecs

6

import pandas

7

import jieba

8

9

#==========词料库构建===============

10

def Create_corpus(file):

11

filePaths = []

12

fileContents=[]

13

for root, dirs, files in os.walk(file):

14

# os.path.join()方法拼接文件名返回所有文件的路径,并储存在变量filePaths中

15

for name in files:

16

filePath=os.path.join(root, name)

17

filePaths.append(filePath)

18

f = codecs.open(filePath, 'r', 'utf-8')

19

fileContent = f.read()

20

f.close()

21

fileContents.append(fileContent)

22

#codecs.open()方法打开每个文件,用文件的read()方法依次读取其中的文本,将所有文本内容依次储存到变量fileContenst中,然后close()方法关闭文件。

23

#创建数据框corpos,添加filePaths和fileContents两个变量作为数组

24

corpos = pandas.DataFrame({'filePath': filePaths,'fileContent': fileContents})

25

return corpos

26

27

#============中文分词===============

28

def Word_segmentation(corpos):

29

segments = []

30

filePaths = []

31

#遍历语料库的每一行数据,得到的row为一个个Series,index为key

32

for index, row in corpos.iterrows():

33

print(row)

34

filePath = row['filePath']#获取每一个row中filePath对应的文件路径

35

fileContent = row['fileContent']#获取row中fileContent对应的每一个文本内容

36

segs = jieba.cut(fileContent)#对文本进行分词

37

for seg in segs:

38

segments.append(seg)#分词结果保存到变量segments中

39

filePaths.append(filePath)#对应的文件路径保存到变量filepaths中

40

#将分词结果及对应文件路径添加到数据框中

41

segmentDataFrame = pandas.DataFrame({'segment': segments,'filePath': filePaths})

42

print(segmentDataFrame)

43

return

44

45

corpos=Create_corpus("F:\医学大数据课题\AI_SLE\AI_SLE_TWO\TEST_DATA")

46

Word_segmentation(corpos)

实现效果:

喜欢记得点赞,在看,收藏,

关注V订阅号:数据杂坛,获取数据集,完整代码和效果,将持续更新!

标签: #python进行分词