Python切分文本(将文本文档切分为词列表)

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_38314865/article/details/84197553

对于一个句子,一种简单的方法是使用split()

a = 'This is an apple. Do you like apple?'
b = a.split()
print(b) # ['This', 'is', 'an', 'apple.', 'Do', 'you', 'like', 'apple?']

可以看到切分结果不错,但标点符号也当成了词的一部分,可以使用正则表达式来切分句子,其中分隔符是除字母,数字外的任意字符串。

import re

a = 'This is an apple. Do you like apple?'
b = re.split(r'\W+', a)
print(b) # ['This', 'is', 'an', 'apple', 'Do', 'you', 'like', 'apple', '']

得到的词列表已不包含符号,但是含有空字符串,同时单词也混有大小写,将其改进得到

import re

a = 'This is an apple. Do you like apple?'
b = re.split(r'\W+', a)
c = [word.lower() for word in b if len(word) > 0]
print(c) # ['this', 'is', 'an', 'apple', 'do', 'you', 'like', 'apple']

猜你喜欢

转载自blog.csdn.net/weixin_38314865/article/details/84197553
今日推荐