1、问题背景
用Python实现一个分词的功能。即从一段英文中,提取所有单词(不重复),并记录单词出现的频率。这个功能是比较好做的,直接就判断单词的分隔符在哪里?比如“I love China!And you?”这句话空格肯定是单词之间的分隔符,另外一些标点符号也是单词之间的分隔符。
2、解决思路
这里有三种办法: 1)一个个字符遍历,遇到疑似分隔符的东西,就换成空格(便于后面文件读词) 2)直接在遍历的时候判断是不是分隔符 3)确定分隔符的位置,一般来讲start就是0,然后end去找,直到遇到不是字母的那个就是分隔符,依次类推
3、实现方法
本文采取的思路是方法一,代码如下:
f=open("emma_lexicon\sentencce.txt",'r' )
st=f.read()
lst2=[i for i in st if i.isalnum()==False and i!="_"]
for k in lst2:
st=st.replace(k,' ')
这样就把所有的非字母分隔符(严格来说是字母和数字,可以去查isalnum()这个函数的用法)的字符换成了空格。
用Python文件读功能取词,生成列表.代码如下:
st=st.strip().lower().split()
dict={}
for j in st:
if j in dict:
dict[j]+=1
else:
dict[j]=1
print(dict)
learn_dictTurnToTxt(dict)
f.close()
字典数据输出到文本文档的函数代码:
def learn_dictTurnToTxt(dict):
f=open("emma_lexicon\dictTurnToTxt.txt",'w')
for i in dict:
s=i+" "+str(dict[i])+'\n'
f.write(s)
f.close()
输出结果是:
https://blog.csdn.net/qq_41286751/article/details/120961935
4、代码
本文实现分词全代码,粘贴即可立马跑起来。
def learn_dictTurnToTxt(dict):
f=open("emma_lexicon\dictTurnToTxt.txt",'w')
for i in dict:
s=i.ljust(15)[:15]+str(dict[i])+'\n'
f.write(s)
f.close()
def learn_dictTurnToCSV(dict):
f=open("emma_lexicon\dictTurnToCSV.csv",'w')
for i in dict:
s=i.ljust(15)[:15]+str(dict[i])+'\n'
f.write(s)
f.close()
def learn_splitWord():
f=open("emma_lexicon\sentencce.txt",'r' )
st=f.read()
lst2=[i for i in st if i.isalnum()==False and i!="_"]
for k in lst2:
st=st.replace(k,' ')
st=st.strip().lower().split()
dict={}
for j in st:
if j in dict:
dict[j]+=1
else:
dict[j]=1
for a in dict:
s = (a+" ")[:15]+str(dict[a])
print(s)
learn_dictTurnToTxt(dict)
f.close()
learn_splitWord()
5、注意事项
注意emma_lexicon这是个文件夹,跟你创建的.py文件是在同一个目录下面,然后生成的文件是在这个文件夹emma_lexicon下面。注意前面取词用到了这个文件下面的sentencce.txt文本,其实就是随便一段英文短文。文本也提供在这里:
There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.
May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.
The happiest of people don’t necessarily have the best of everything;they just make the most of everything that comes along their way.Happiness lies for those who cry,those who hurt, those who have searched,and those who have tried,for only they can appreciate the importance of people who have touched their lives.Love begins with a smile,grows with a kiss and ends with a tear.The brightest future will always be based on a forgotten past, you can’t go on well in lifeuntil you let go of your past failures and heartaches.
注意,文件之间的关系,贴图: 喜欢就点个赞叭!
|