【发布时间】:2018-10-22 15:49:46
【问题描述】:
给定一个词汇表:{'A': 3, 'B': 4, 'C': 5, 'AB':6} 和一个应分段的句子:ABCAB。
我需要创建这句话的所有可能组合,例如
[['A', 'B', 'C', 'A', 'B'], ['A', 'B', 'C', 'AB'], ['AB', 'C', 'AB'], ['AB', 'C', 'A', 'B']]
这就是我所拥有的:
def find_words(sentence):
for i in range(len(sentence)):
for word_length in range(1, max_word_length + 1):
word = sentence[i:i+word_length]
print(word)
if word not in test_dict:
continue
if i + word_length <= len(sentence):
if word.startswith(sentence[0]) and word not in words and word not in ''.join(words):
words.append(word)
else:
continue
next_position = i + word_length
if next_position >= len(sentence):
continue
else:
find_ngrams(sentence[next_position:])
return words
但它只返回一个列表。
我也在 itertools 中寻找有用的东西,但我找不到任何明显有用的东西。不过可能错过了。
【问题讨论】:
-
在您的示例中,
|是否表示逗号? -
我想我会分两个阶段进行。 1:尝试用工具中最小的元素完成给定的句子。 2:尝试将解决方案中的元素合并到更大的工具中。
-
@ninesalt 是的,它也可以是空格或类似的东西
-
请用逗号代替竖线修正您的示例列表,并添加普通样式
'。 -
词汇表中的数字有什么意义?
标签: python string python-3.x list text-segmentation