编程语言
首页 > 编程语言> > 笨办法学Python3   ex49

笨办法学Python3   ex49

作者:互联网

 笨办法学Python3   ex49  被测试代码, 分析了ex49 Python老大 Zed写的源码, 自己学着写了一个有一点不一样, 还没有写最后几个抛错类和sentence类, 不知道直接用书上的,会不会有问题.

不管了, 先试着传入列表,简单的测试一下, 为了看出三个分析者拿到的word_list是什么糖果, 直接在三个函数第一行就打印了拿到的糖果. 测试文件还没写, 感觉有点烧脑子.

 下面是运行结果 

我在parse_sub里: [('noun', 'fighter'), ('throw', 'will'), ('verb', 'kill'), ('throw', 'the'), ('noun', 'bear'), ('throw', 'and'), ('noun', 'beefs')]

('noun', 'fighter')

我在parse_verb里: [('verb', 'kill'), ('throw', 'the'), ('noun', 'bear'), ('throw', 'and'), ('noun', 'beefs')]

('verb', 'kill')

我在parse_obj里: [('noun', 'bear'), ('throw', 'and'), ('noun', 'beefs')]

('noun', 'bear')

 下面是被测试源文件

# %%writefile parser.py

li =[('throw', 'the'), ('noun', 'fighter'),('throw', 'will'),('verb', 'kill'),('throw', 'the'),('noun', 'bear')]

def peek(word_list):    #   [('throw' , 'the')('noun', 'car'), ('verb', 'hit'),('noun', 'me')]
    if word_list:
        word = word_list[0]  
        return word[0]  #  return 'noun'
    else:
        pass

def match(word_list):      # 整理者  分析前整理拿到的列表
    if word_list:
        word = word_list.pop(0)  #  分析一个删除一个,避免后面重复工作
        return word
    else:
        pass

def parse_sub(word_list):  #  主语分析者
    new_word_list = skip(word_list)
    print('我在parse_sub里:', new_word_list)
    if peek(new_word_list) == 'noun':
        return match(new_word_list)
    else:
        print('我需要主语')

def parse_verb(word_list):   # 谓语分析者
    new_word_list = skip(word_list)
    print('我在parse_verb里:', new_word_list)
    if peek(new_word_list) == 'verb':
        return match(new_word_list)
    else:
        print('我需要谓语')   

def parse_obj(word_list):     # 宾语分析者
    new_word_list = skip(word_list)
    print('我在parse_obj里:', new_word_list)
    if peek(new_word_list) == 'noun':
        return match(new_word_list)
    elif peek(new_word_list) == 'direction':
        return match(new_word_list)
    elif peek(new_word_list) == 'verb':
        return ('noun', 'Someone')
    else:
        print('我需要宾语')

def skip(word_list):           #垃圾分析者
    while peek(word_list) == 'throw': 
        word_list.pop(0)
    
    return word_list

print(parse_sub(li))
print(parse_verb(li))
print(parse_obj(li))

 

 

标签:noun,list,ex49,parse,verb,new,word,笨办法,Python3
来源: https://blog.csdn.net/wggglggg/article/details/115237931