python怎么对单词分词,Python:查找所有可能的带有字符序列的单词组合(分词)...

本文介绍了一种通过Python的itertools库实现字符序列的所有可能分词组合的方法。针对给定的字符列表,利用itertools.product生成所有可能的分词方案,并确保了分词顺序从左至右的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm doing some word segmentation experiments like the followings.

lst is a sequence of characters, and output is all the possible words.

lst = ['a', 'b', 'c', 'd']

def foo(lst):

...

return output

output = [['a', 'b', 'c', 'd'],

['ab', 'c', 'd'],

['a', 'bc', 'd'],

['a', 'b', 'cd'],

['ab', 'cd'],

['abc', 'd'],

['a', 'bcd'],

['abcd']]

I've checked combinations and permutations in itertools library,

and also tried combinatorics.

However, it seems that I'm looking at the wrong side because this is not pure permutation and combinations...

It seems that I can achieve this by using lots of loops, but the efficiency might be low.

EDIT

The word order is important so combinations like ['ba', 'dc'] or ['cd', 'ab'] are not valid.

The order should always be from left to right.

EDIT

@Stuart's solution doesn't work in Python 2.7.6

EDIT

@Stuart's solution does work in Python 2.7.6, see the comments below.

解决方案

itertools.product should indeed be able to help you.

The idea is this:-

Consider A1, A2, ..., AN separated by slabs. There will be N-1 slabs.

If there is a slab there is a segmentation. If there is no slab, there is a join.

Thus, for a given sequence of length N, you should have 2^(N-1) such combinations.

Just like the below

import itertools

lst = ['a', 'b', 'c', 'd']

combinatorics = itertools.product([True, False], repeat=len(lst) - 1)

solution = []

for combination in combinatorics:

i = 0

one_such_combination = [lst[i]]

for slab in combination:

i += 1

if not slab: # there is a join

one_such_combination[-1] += lst[i]

else:

one_such_combination += [lst[i]]

solution.append(one_such_combination)

print solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值