0

我正在设计一个程序,它查看单词列表,并计算有多少单词中只有字母 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。我应该怎么做它会拒绝任何有禁止字母的单词?

4

3 回答 3

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
于 2013-02-09T04:28:46.003 回答
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()
于 2013-02-09T04:53:20.967 回答
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。

于 2013-02-09T06:54:53.960 回答