使用Python解析字符串?

use*_*012 6 python string-matching

给定一个字符串,例如'helloyellowellow',解析给定字符串中的所有有效字符串.(例如:[[地狱,你好,黄色],[低,低] ........]

我正在寻找最优化的编写代码的方法.这是我的,但我不确定这是不是最好的方法.

完全披露 - 这是一个面试问题

master = []

#   Dictionary for us to look up words   
def is_word(inputstr):
    #returns True/False


def processstring(fstr,secstr,li):
    if is_word(fstr): 
        li.append(fstr)
    if len(secstr) == 0:
        if len(li) != 0:
            master.append(li)
        return
    processstring(fstr+secstr[0], secstr[1:len(secstr)],li)



def wrapperprocess(inpstr):
    li = []
    if len(inpstr) == 0:
        return
    processstring('',inpstr,li)
    wrapperprocess(inpstr[1:len(inpstr)])


wrapperprocess('helloyellowellow')
print master
Run Code Online (Sandbox Code Playgroud)

daw*_*awg 2

你可以这样做:

tgt='helloyellowellow'

with open('/usr/share/dict/words') as f:
    for word in f:
        word=word.strip()
        if word in tgt and len(word)>1:
            print word
Run Code Online (Sandbox Code Playgroud)

印刷:

el
ell
he
hell
hello
lo
low
loy
ow
owe
we
well
ye
yell
yellow
Run Code Online (Sandbox Code Playgroud)

如果您只是寻找is_word未定义的函数,您可以使用如下方法:

def is_word(word, dic='/usr/share/dict/words'):
    if not hasattr(is_word, 'words'):
        with open(dic) as f:
            is_word.words={word.strip() for word in f}

    return word in is_word.words and len(word)>1
Run Code Online (Sandbox Code Playgroud)

作为默认数据结构,Python 集的平均查找时间为 O(1)。你不太可能自己写出更快的东西。

  • 在这种情况下什么是“有效”?在我的(旧的、慢速的)计算机上,它的执行时间为 88 毫秒。仅在 Python 中打印“hello”就需要 22 毫秒,因此多花 60 毫秒就相当快了。一次只有一个单词被记忆,所以它的记忆效率非常高。由于我花了大约 30 秒来编写,所以程序员的效率相当高。您希望通过什么方式变得更有效率?;-) (2认同)