我有一些推文,我想分成几个字。大多数工作正常,除非人们组合如:trumpisamoron
或makeamericagreatagain
这样的字词。但是,还有password
之类的内容,不应该分为pass
和word
。
我知道nltk包有一个punkt tokenizer
模块,可以智能地分割句子。是否有类似的话语?即使它不在nltk包中?
注意:password -> pass + word
的示例比分裂词问题少得多。
答案 0 :(得分:1)
参考:我对另一个问题的回答 - Need to split #tags to text。
我所做的答案中的变化是:(1)获得WORDS
的不同语料库和(2)添加def memo(f)
以加快进程。您可能需要根据您正在使用的域添加/使用语料库。
检查Word Segmentation Task来自Norvig的工作。
from __future__ import division
from collections import Counter
import re, nltk
from datetime import datetime
WORDS = nltk.corpus.reuters.words() + nltk.corpus.words.words()
COUNTS = Counter(WORDS)
def memo(f):
"Memoize function f, whose args must all be hashable."
cache = {}
def fmemo(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
fmemo.cache = cache
return fmemo
def pdist(counter):
"Make a probability distribution, given evidence from a Counter."
N = sum(counter.values())
return lambda x: counter[x]/N
P = pdist(COUNTS)
def Pwords(words):
"Probability of words, assuming each word is independent of others."
return product(P(w) for w in words)
def product(nums):
"Multiply the numbers together. (Like `sum`, but with multiplication.)"
result = 1
for x in nums:
result *= x
return result
def splits(text, start=0, L=20):
"Return a list of all (first, rest) pairs; start <= len(first) <= L."
return [(text[:i], text[i:])
for i in range(start, min(len(text), L)+1)]
@memo
def segment(text):
"Return a list of words that is the most probable segmentation of text."
if not text:
return []
else:
candidates = ([first] + segment(rest)
for (first, rest) in splits(text, 1))
return max(candidates, key=Pwords)
print segment('password') # ['password']
print segment('makeamericagreatagain') # ['make', 'america', 'great', 'again']
print segment('trumpisamoron') # ['trump', 'is', 'a', 'moron']
print segment('narcisticidiots') # ['narcistic', 'idiot', 's']
有时,如果单词被溢出到较小的标记中,那么单词在WORDS
字典中不存在的可能性就会更高。
在最后一段中,它将narcisticidiots
分为3个令牌,因为我们的idiots
中没有令牌WORDS
。
# Check for sample word 'idiots'
if 'idiots' in WORDS:
print("YES")
else:
print("NO")
您可以将新用户定义的字词添加到WORDS
。
.
.
user_words = []
user_words.append('idiots')
WORDS+=user_words
COUNTS = Counter(WORDS)
.
.
.
print segment('narcisticidiots') # ['narcistic', 'idiots']
为了更好的解决方案,你可以使用bigram / trigram。