由于一些技术问题,所有句子中的空格都被移除(除了句号)。
mystring='thisisonlyatest. andhereisanothersentense'
有没有办法在Python中得到这样的可读输出…
“this is only a test. and here is another sentense.”
回答:
如果你有一份常用有效单词的列表(可以在互联网上找到不同语言的版本),你可以获取所有前缀,检查它们是否为有效单词,并递归地重复处理句子的剩余部分。使用记忆化技术来避免对相同后缀的重复计算。
这里是一个Python的例子。使用lru_cache
注解为函数添加了记忆化功能,这样每个后缀的句子只计算一次,与第一部分如何分割无关。请注意,words
是一个set
,用于O(1)查找。前缀树也非常适合这种情况。
words = {"this", "his", "is", "only", "a", "at", "ate", "test", "and", "here", "her", "is", "an", "other", "another", "sent", "sentense", "tense", "and", "thousands", "more"}max_len = max(map(len, words))import functoolsfunctools.lru_cache(None)def find_sentences(text): if len(text) == 0: yield [] else: for i in range(min(max_len, len(text)) + 1): prefix, suffix = text[:i], text[i:] if prefix in words: for rest in find_sentences(suffix): yield [prefix] + restmystring = 'thisisonlyatest. andhereisanothersentense'for text in mystring.split(". "): print(repr(text)) for sentence in find_sentences(text): print(sentence)
这将为你提供一个有效的(但可能无意义的)分割句子的方法列表。这些方法可能足够少,你可以手动选择正确的那个;否则,你可能需要添加另一个后处理步骤,例如使用合适的NLP框架进行词性分析。