我需要使用python将这个单词拆分成一个句子,有什么办法吗?
strng = 'thisisastring'
o / p:
this is a string
正如Peter和Mark已经指出的那样,这是一个棘手的问题,没有简单或独特的解决方案。您当然需要列出可能的单词。然后,最好的选择是使用回溯。
这是一个返回元组列表的简单函数,其中每个元组代表一个可能的句子。
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"
不是单词,因此它只会失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句