Need to split #tags to text

偶尔善良 提交于 2020-01-17 13:46:11

问题


I Need to split #tags to meaningful words in an automated way.

Sample Input:

  • iloveusa
  • mycrushlike
  • mydadhero

Sample Output

  • i love usa
  • my crush like
  • my dad hero

Any utility or open API that I can use to achieve this?


回答1:


Check - Word Segmentation Task from Norvig's work.

from __future__ import division
from collections import Counter
import re, nltk

WORDS = nltk.corpus.brown.words()
COUNTS = Counter(WORDS)

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)]

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('iloveusa')     # ['i', 'love', 'us', 'a']
print segment('mycrushlike')  # ['my', 'crush', 'like']
print segment('mydadhero')    # ['my', 'dad', 'hero']

For better solution than this you can use bigram/trigram.

More examples at : Word Segmentation Task



来源:https://stackoverflow.com/questions/38621703/need-to-split-tags-to-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!