![](/img/trans.png)
[英]Split a string at uppercase characters and numbers ignoring consecutive uppercase letters in Python
[英]how to split a string without any special characters ,uppercase or numbers in a word
我需要使用 python 将这个词分成一个句子。有没有办法做到这一点?
strng = 'thisisastring'
o/p:
this is a string
正如彼得和马克已经指出的那样,这是一个难题,没有简单或独特的解决方案。 你当然需要一个可能的单词列表来开始。 可能你最好的选择是使用回溯。
这是一个简单的 function,它返回一个元组列表,其中每个元组代表一个可能的句子。
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")
。
该算法的基本思想是将字符串一次拆分一个单词。 因此,第一个近似值如下,它采用第一个可能适合的单词,然后尝试拆分字符串的 rest。
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
但是,这通常不起作用。 在您的示例中,一旦您到达 rest 为"astring"
,该算法可能会尝试"as"
作为下一个可能的单词,但因为"tring"
不是一个单词,它只是失败了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.