【问题标题】:Program that searches for words that use certain letters搜索使用某些字母的单词的程序
【发布时间】:2013-01-24 22:46:37
【问题描述】:

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

【问题讨论】:

    标签: python string search loops


    【解决方案1】:

    更正您的测试功能:

    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
    

    【讨论】:

    • 我想说,如果函数的目的是搜索字母“python”,那么你应该在函数内部定义它,而不是传入python 变量。
    【解决方案2】:
    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()
    

    【讨论】:

      【解决方案3】:

      欢迎使用正则表达式:

      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。

      【讨论】:

        猜你喜欢
        • 2021-06-22
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 2014-06-11
        • 1970-01-01
        • 1970-01-01
        • 2012-12-20
        • 2017-07-14
        相关资源
        最近更新 更多