2013-02-09 45 views
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() 

然而,我的代碼將返回的單詞數不正確,例如,它會返回單詞「xylophonist」如果我把打印語句吧因爲它有Python中的字母。我該怎麼做纔會拒絕任何禁止發信的詞?

回答

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 
+3

我想說,如果函數的目的是搜索字母「python」,那麼應該在函數內部定義它,而不是傳遞一個'python'變量。 – Interrobang 2013-02-09 04:29:47

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() 
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')

如果你不想走這條路線,我建議你返回false,如果字符串的任何字母不是p,y,t,h,o或n。

相關問題