搜索使用特定字母的单词的程序

0 投票
3 回答
2741 浏览
提问于 2025-04-17 15:19

我正在设计一个程序,它会查看一个单词列表,并计算其中有多少个单词只包含字母 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 个回答

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。

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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

撰写回答