《think in python》学习-9

think in python
think in python -9

案例分析:文字游戏

从文本文件中读取文字

作者提供了一个文本文件words.txt 地址
本章后面案例也会用带该文件中的词组

fin = open("words.txt")
for line in fin:
    word = line.strip()
    print word

练习

  1. 编写一个程序,读入words.txt并且打印出长度超过20个字符的单词
    fin = open("words.txt")
    for line in fin:
        word = line.strip()
        if len(word)>20:
            print word
    
  2. 编写一个函数 当给定单词不包含字母e的时候 返回True
    def has_noo_e(s):
        return s.find('e')==-1    
    
  3. 修改练习1,打印出不包含e的单词,以及数量
    def find_no_e():
    n = 0
    ne = 0
    for line in fin:
        word = line.strip()
        n=n+1
        if   has_noo_e(word):
            print word
            ne = ne+1
    
    print ne,n
    
  4. 编写一个avoids,接受一个单词,以及一个包含禁止字母的字符串,当单词不含任何禁止字幕时 返回True
    def avoids(s,no):
        for letter in s:
            if letter in no:
                return False
        return True
    
  5. 编写一个 uses_only函数,接受一个单词以及字母组成的字符串,当单词只由这些字母组成时返回true
    def uses_only(word,s):
        for i in s:
            if i in word:
                print 'yes'
            else :
                print 'NO'
    
  6. 编写一个users_all ,接受一个单词以及由需要的字母组成的字符串,当需要的所有的字母出现了至少一次时返回true
        def uses_all(w,m):
            for letter in m:
                if letter not in w:
                return False
            return True
    
  7. 编写一个is_abecedarian函数,如果单词中的字母是按照字母表顺序(重复字母也算ok)则返回true
    def is_abecedarian(n):
        return n == "".join(sorted(n))
    
原文地址:https://www.cnblogs.com/iyueyao/p/4190001.html