马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
n元文法(n-gram)在自然语言处理中是指文本中连续出现的n个元素。例如以字符为单位文本数据的n元文法是如下的形式(空格以下划线表示): 
文本数据:…to_be_or_not_to_be… 
一元文法(1-gram):…, t, o, _, b, e, _, o, r, _, n, o, t, _, t, o, _, b, e, … 
二元文法(2-gram):…, to, o_, _b, be, e_, _o, or, r_, _n, no, ot, t_, _t, to, o_, _b, be, … 
三元文法(3-gram):…, to_, o_b, _be, be_, e_o, _or, or_, r_n, _no, not, ot_, t_t, _to, to_, o_b, _be, … 
请编写一个函数,返回所给文本以字符为单位的n元文法短语。文本字符串以及n值由函数的参数输入。使用列表容器返回的各短语,重复短语只出现一次,列表按升序排序。 
例: 
函数定义:def ngram(a_str, n), 
计算返回值:ngram('to_be_or_not_to_be', 6) 
['_be_or', '_not_t', '_or_no', '_to_be', 'be_or_', 'e_or_n', 'not_to', 'o_be_o', 'or_not', 'ot_to_', 'r_not_', 't_to_b', 'to_be_']
 本帖最后由 jtxs0000 于 2020-12-29 11:11 编辑 
基础不扎实,我暂时只能想到这个
 - def ngram(a_str, n):
 
 -     a_str = list(a_str)
 
 -     res = []
 
 -     while a_str:
 
 -         if len(a_str) <= n:
 
 -             res.append("".join(a_str))
 
 -             del a_str[:]
 
 -         else:
 
 -             res.append("".join(a_str[:n]))
 
 -             del a_str[0]
 
 -     return sorted(set(res))
 
  复制代码 
 
 
 |