搜索使用某些字母的单词的程序

时间:2013-02-09 04:25:52

标签: python string search loops

我正在设计一个查看单词列表的程序,并计算有多少单词只包含字母p,y,t,h,o和n。

到目前为止,我的代码是:

def find_python(string, python):
 """searches for the letters 'python' in the word."""
 for eachLetter in python:
    if eachLetter not in string:
        return False
 return True

def main():
 python = 'python'
 how_many = 0

 try:
 fin = open('words.txt')#open the file
 except:
     print("No, no, file no here") #if file is not found
 for eachLine in fin:
    string = eachLine
    find_python(string, python)
if find_python(string, python) == True:
    how_many = how_many + 1#increment count if word found
 print how_many#print out count
 fin.close()#close the file

if __name__ == '__main__':
main()

但是,我的代码返回的单词数量不正确,例如,如果我输入print语句,它将返回单词'xylophonist',因为它中包含字母python。我应该怎么做才会拒绝任何禁止使用的字?

3 个答案:

答案 0 :(得分:3)

更正您的测试功能:

def find_python(string, python):
 """searches for the letters 'python' in the word.
    return True, if string contains only letters from python.
 """
 for eachLetter in string:
    if eachLetter not in python:
        return False
 return True

答案 1 :(得分:0)

from os import listdir

def diagy(letters,li):
    return sum( any(c in letters for c in word) for word in li )

def main():
    dir_search = 'the_dir_in_which\\to_find\\the_file\\'
    filename = 'words.txt'

    if filename in listdir(dir_search):
        with open(dir_search + 'words.txt',) as f:
            li = f.read().split()
        for what in ('pythona','pyth','py','ame'):
            print '%s  %d' % (what, diagy(what,li))

    else:
        print("No, no, filename %r is not in %s" % (filename,dir_search))

if __name__ == '__main__':
    main()

答案 2 :(得分:0)

欢迎来到正则表达式:

import re
line = "hello python said the xylophonist in the ythoonp"
words = re.findall(r'\b[python]+\b',line)
print words

返回

['python', 'ythoonp']

如果您想要查找实际单词python出现的次数,那么您应该发出re.findall(r'\bpython\b')

如果你不想走这条路线,如果字符串中的任何字母不是p,y,t,h,o或n,我建议你返回false。