我需要用python把这个词拆成一个句子.有什么办法吗?
strng = 'thisisastring'
op:
this is a string
正如彼得和马克已经指出的,这是一个很难的问题,没有简单或独特的解决方案。 你当然需要一个可能的单词列表来开始。 那么可能你最好的选择就是使用回溯法。
这里有一个简单的函数,可以返回一个元组列表,其中每个元组代表一个可能的句子。
words = [
"a", "as", "is", "light", "or", "project",
"projector", "string", "the", "this"
]
def findPhrase(text):
result = []
for word in words:
if text == word:
# if the entire text is the word, there is no need
# to look at the (now empty) rest.
result.append((word,))
elif text.startswith(word):
# if the text starts with the current word, try to
# find all partitions of the remaining text
rest = findPhrase(text[len(word):])
# if there are any such partitions, add them all to our
# list of results, and put the current word in front
# of each of these solutions
for solution in rest:
result.append((word,) + solution)
return result
注意,我使用了 (word,)
在这段代码中把它变成一个元组,所以我们可以简单地把它加在一起,即 ("is",) + ("a", "string") -> ("is", "a", "string")
.
该算法的基本思想是每次拆分一个字。 所以,第一个近似的方法是如下,它取第一个可能适合的单词,然后尝试分割字符串的其余部分。
def my_split(text):
if text == "":
return []
for word in words:
if text.startswith(word):
rest = text[len(word):]
result = [word] + my_split(rest)
return result
然而,这在一般情况下是行不通的。 在你的例子中,一旦你达到其余的字被 "astring"
,然后算法可能会尝试 "as"
作为下一个可能的词,但由于 "tring"
不是一个字,根本就是失败。