《笨辦法學Python》筆記35-----更復雜的用戶輸入

更復雜的用戶輸入

這一章是分析用戶輸入,有點人工智能的意思了牍白,哈哈脊凰。

用戶在輸入命令時,open dooropen the door應當是一個意思茂腥,現(xiàn)在交給程序去判斷狸涌。

首先得從英語組成上分析

  • 句子由單詞組成

  • 單詞與單詞之間通過空格間隔

  • 單詞有動詞、名詞最岗、修飾詞帕胆、數字等構成

  • 句子的意思由語法控制

所以分析一個句子,首先得將它拆分成單詞般渡,然后分析每個單詞的類型惶楼,最后將其重組為指令右蹦。

獲取用戶輸入,拆分成單詞

stuff = raw_input('> ')

words = stuff.split() #返回一個列表

分析單詞類型

使用(type,word)元組來保存單詞類型對

first_word = ('direction','north')

second_word = ('verb','go')

sentence = [first_word,second_word]

單元測試

書中提供了測試用例歼捐,

from nose.tools import *
from EX48 import lexicon

def test_directions():
    assert_equal(lexicon.scan("north"),[('direction','north')])

    result = lexicon.scan("north south east")

    assert_equal(result,[('direction','north'),
                        ('direction','south'),
                        ('direction','east')])

def test_verbs():
    assert_equal(lexicon.scan("go"),[('verb','go')])

    result = lexicon.scan("go kill eat")

    assert_equal(result,[('verb','go'),
                        ('verb','kill'),
                        ('verb','eat')])


def test_stops():
    assert_equal(lexicon.scan("the"),[('stop','the')])

    result = lexicon.scan("the in of")

    assert_equal(result, [('stop','the'),
                        ('stop','in'),
                        ('stop','of')])

def test_nouns():
    assert_equal(lexicon.scan("bear"),[('noun','bear')])

    result = lexicon.scan("bear princess")

    assert_equal(result, [('noun','bear'),
                        ('noun','princess')])

def test_numbers():
    assert_equal(lexicon.scan('1234'),[('number',1234)])

    result = lexicon.scan("3 91234")

    assert_equal(result,[('number',3),
                        ('number',91234)])

def test_errors():
    assert_equal(lexicon.scan('ASDFADFASDF'),[('error','ASDFADFASDF')])
    result = lexicon.scan("bear IAS princess")

    assert_equal(result,[('noun','bear'),
                        ('error','IAS'),
                        ('noun','princess')])

根據測試用例寫出詞匯掃描器。

通過assert_equal函數可以發(fā)現(xiàn)

  • lexicon中有個帶字符串參數的scan函數

  • 詞匯類型有‘direction’晨汹、'number'豹储、'noun'、'stop'淘这、'verb'剥扣、'error'

  • 再增加一個名為'unkown'的類型以便收集預定詞匯表中沒有的單詞

  • scan函數的返回值是一個列表,列表的元素是(type,word)元組對

詞匯掃描器

應該有個預定列表來保存常用的單詞和它所代表的類型

當獲取用戶輸入后铝穷,拆分成詞钠怯,與預定的詞匯類型表對比獲取單詞類型,返回多個(type,word)元組

def scan(stuff):
    sentence = []
    directions = ['north','south','east']
    verbs = ['go','kill','eat']
    stops = ['in','of','the']
    nouns = ['bear','princess']
    numbers = [3,91234,1234]
    errors = ['IAS','ASDFADFASDF']
    words = stuff.split()

    for word in words:
        if word in directions:
            sentence.append(('direction',word))
        elif word in verbs:
            sentence.append(('verb',word))
        elif word in stops:
            sentence.append(('stop',word))
        elif word in nouns:
            sentence.append(('noun',word))
        elif word in errors:
            sentence.append(('error',word))
        elif int(word) in numbers:
            sentence.append(('number',int(word)))
        else:
            sentence.append(('unkown',word))
    return sentence

執(zhí)行nosetests

damao@damao:~/Documents/ex48$ nosetests
.........
~----------------------------------------------------------------------
Ran 9 tests in 0.005s

OK

這個掃描器可以再改進曙聂。

def scan(stuff):
    sentence = []
    directions = ['north','south','east']
    verbs = ['go','kill','eat']
    stops = ['in','of','the']
    nouns = ['bear','princess']
    numbers = [3,91234,1234]
    errors = ['IAS','ASDFADFASDF']
    words = stuff.split()

    for word in words:
        try:
            intword = int(word)
            sentence.append(('number',int(word)))
        except ValueError:
            if word in directions:
                sentence.append(('direction',word))
            elif word in verbs:
                sentence.append(('verb',word))
            elif word in stops:
                sentence.append(('stop',word))
            elif word in nouns:
                sentence.append(('noun',word))
            elif word in errors:
                sentence.append(('error',word))     
            else:
                sentence.append(('unkown',word))
    return sentence


print scan("go north")
print scan("kill the princess")
print scan("eat the bear")
print scan("open the door and smack the bear in the nose")
print scan("open 1234 door")


單獨運行輸出效果

damao@damao:~/Documents/ex48/EX48$ python lexicon.py
[('verb', 'go'), ('direction', 'north')]
[('verb', 'kill'), ('stop', 'the'), ('noun', 'princess')]
[('verb', 'eat'), ('stop', 'the'), ('noun', 'bear')]
[('unkown', 'open'), ('stop', 'the'), ('unkown', 'door'), ('unkown', 'and'), ('unkown', 'smack'), ('stop', 'the'), ('noun', 'bear'), ('stop', 'in'), ('stop', 'the'), ('unkown', 'nose')]
[('unkown', 'open'), ('number', 1234), ('unkown', 'door')]

可以正常輸入元組列表晦炊。

使用骨架目錄,以一個新項目形式生成宁脊,項目名字叫EX48

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末断国,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子榆苞,更是在濱河造成了極大的恐慌稳衬,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件坐漏,死亡現(xiàn)場離奇詭異薄疚,居然都是意外死亡,警方通過查閱死者的電腦和手機赊琳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門街夭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人慨畸,你說我怎么就攤上這事莱坎。” “怎么了寸士?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵檐什,是天一觀的道長。 經常有香客問我弱卡,道長乃正,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任婶博,我火速辦了婚禮瓮具,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己名党,他們只是感情好叹阔,可當我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著传睹,像睡著了一般耳幢。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上欧啤,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天睛藻,我揣著相機與錄音,去河邊找鬼邢隧。 笑死店印,一個胖子當著我的面吹牛,可吹牛的內容都是我干的倒慧。 我是一名探鬼主播按摘,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼迫靖!你這毒婦竟也來了院峡?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤系宜,失蹤者是張志新(化名)和其女友劉穎照激,沒想到半個月后,有當地人在樹林里發(fā)現(xiàn)了一具尸體盹牧,經...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡俩垃,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了汰寓。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片口柳。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖有滑,靈堂內的尸體忽然破棺而出跃闹,到底是詐尸還是另有隱情,我是刑警寧澤毛好,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布望艺,位于F島的核電站,受9級特大地震影響肌访,放射性物質發(fā)生泄漏找默。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一吼驶、第九天 我趴在偏房一處隱蔽的房頂上張望惩激。 院中可真熱鬧店煞,春花似錦、人聲如沸风钻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽骡技。三九已至衩椒,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間哮兰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工苟弛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留喝滞,地道東北人。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓膏秫,卻偏偏與公主長得像右遭,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子缤削,可洞房花燭夜當晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內容