- 解决方案1:
让这些大块的认为你的句子作为算盘的珠子,每个珠子组成部分字符串,珠可以向左或向右移动以产生排列。每个片段的位置固定在两个相邻片段之间。 在目前的情况下,珠会:
(more)(recen)(t)(ly)(the)(develop)(ment,)(wh)(ich)(is)(a)(po)(ten)(t)
这解决了2子问题:
一)珠是一个单位,所以我们不关心的“更多”珠即排列中排列是不可能的。
b)珠子的顺序是恒定的,只有它们之间的间距发生变化。即“更多”将总是在“重新”之前等等。
现在,产生的这些珠子,这将给像输出所有排列:
morerecentlythedevelopment,which is a potent
morerecentlythedevelopment,which is a poten t
morerecentlythedevelop ment, wh ich is a po tent
morerecentlythedevelop ment, wh ich is a po ten t
morerecentlythe development,whichisapotent
则得分这些排列基础上,他们是如何从相关的字典很多字包含最正确的结果可以很容易地过滤出。 more recently the development, which is a potent
将比分这确实珠的排列部分高于morerecentlythedevelop ment, wh ich is a po ten t
代码:
import re
def gen_abacus_perms(frags):
if len(frags) == 0:
return []
if len(frags) == 1:
return [frags[0]]
prefix_1 = "{0}{1}".format(frags[0],frags[1])
prefix_2 = "{0} {1}".format(frags[0],frags[1])
if len(frags) == 2:
nres = [prefix_1,prefix_2]
return nres
rem_perms = gen_abacus_perms(frags[2:])
res = ["{0}{1}".format(prefix_1, x) for x in rem_perms] + ["{0} {1}".format(prefix_1, x) for x in rem_perms] + \
["{0}{1}".format(prefix_2, x) for x in rem_perms] + ["{0} {1}".format(prefix_2 , x) for x in rem_perms]
return res
broken = "more recen t ly the develop ment, wh ich is a po ten t"
frags = re.split("\s+",broken)
perms = gen_abacus_perms(frags)
print("\n".join(perms))
演示:http://ideone.com/pt4PSt
- 解决方案#2 :
我会建议一种替代方法,它利用了人们已经开发的文本分析智能,这些智能人员正在研究类似的问题,并研究了依赖字典和语法的大数据语料库。搜索引擎。
我不太了解这样的公共/付费apis,所以我的例子是基于谷歌的结果。
让我们尝试使用谷歌:
- 你可以保持把你的无效条款,谷歌,多传球,并保持在评估基础上的查找字典一些得分的结果。 这里有两个相关的输出,通过使用2遍你的文字:
![enter image description here](https://i.stack.imgur.com/uBUtj.png)
这outout用于第二遍:
![enter image description here](https://i.stack.imgur.com/pTnpD.png)
,让你转换为“ “最近的发展,这是一个有力的”。
要验证转换,您将不得不使用一些相似性算法和评分来筛选出无效/不太好的结果。
一个原始技术可能是使用difflib比较标准化字符串。
>>> import difflib
>>> import re
>>> input = "more recen t ly the develop ment, wh ich is a po ten t "
>>> output = "more recently the development, which is a potent "
>>> input_norm = re.sub(r'\W+', '', input).lower()
>>> output_norm = re.sub(r'\W+', '', output).lower()
>>> input_norm
'morerecentlythedevelopmentwhichisapotent'
>>> output_norm
'morerecentlythedevelopmentwhichisapotent'
>>> difflib.SequenceMatcher(None,input_norm,output_norm).ratio()
1.0
但是,当句子可以按多个顺序排列时,它是如何工作的? “笔更适合当时的人” – DhruvPathak
优雅的方法,但放弃所有空间将其变成一个更难的问题。 OPS描述(“删除不需要的空间”)表明空间永远不会丢失;如果这是正确的,你应该永远不要在分词中寻找片段。 – alexis
@alexis,你说得对,我猜测性能可以提高至少一个数量级,只需计算各种连接的概率,而不是所有的分割。我稍后可能会回来重新阐述我的答案。 – miku