在Python NLTK中,我想对非空字符串进行形态分析
我想用NLTK这个工具对一个没有空格的字符串进行形态分析。
举个例子:
这个字符串是 "societynamebank"
。
我想得到的结果是 ['society', 'name', 'bank']
。
那么,怎么才能在NLTK中得到这个结果呢?
1 个回答
5
这里有一段简单的代码,可能对你有帮助。它使用了pyEnchant字典来进行形态分析:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> tokens=[]
>>> def tokenize(st):
... if not st:return
... for i in xrange(len(st),-1,-1):
... if d.check(st[0:i]):
... tokens.append(st[0:i])
... st=st[i:]
... tokenize(st)
... break
...
>>> tokenize("societynamebank")
>>> tokens
['society', 'name', 'bank']
>>> tokens=[]
>>> tokenize("HelloSirthereissomethingwrongwiththistext")
>>> tokens
['Hello', 'Sir', 'there', 'is', 'something', 'wrong', 'with', 'this', 'text']