簡體   English   中英

搜索使用某些字母的單詞的程序

[英]Program that searches for words that use certain letters

我正在設計一個程序,該程序可以查看單詞列表,並計算其中只有字母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。 我該怎么辦,它將拒絕任何禁止字母的單詞?

更正您的測試功能:

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

歡迎使用正則表達式:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM