此代码未显示正确的ans

2024-10-03 15:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

dictionary = open('dictionary.txt','r')
def main():
    print("part 4")
    part4()
def part4():
    naclcount = 0
    for words in dictionary:
        if 'nacl' in words:
            naclcount = naclcount + 1
    return naclcount
main()

基本上它的答案是25,这是正确的,除了当我把另一个函数在第4部分之前,它将打印为0。你知道吗

def part1():
    vowels = 'aeiouy'
    vowelcount = 0
    for words in dictionary:
        words = words.lower()
        vowelcount = 0
        if len(words) == 8:
            if 's' not in words:
                for letters in words:
                    if letters in vowels:
                        vowelcount += 1
                if vowelcount == 1:
                    print(words)
    return words

Tags: infordictionaryreturnifmaindefopen
2条回答

你能不能把你的另一个函数粘贴上去。除非你展示你的另一个功能,否则问题是不清楚的。你知道吗

从你的问题和密码我推断出来的。我已经修改(清除)了你的代码。看看是否有用。你知道吗

def part4(dictionary):
    words = dictionary.readlines()[0].split(' ')
    nacl_count = 0
    for word in words:
        if word == 'the':
            nacl_count += 1
        #print nacl_count
    return nacl_count


def part1(dictionary):
    words = dictionary.readlines()[0].split(' ')
    words = [word.lower() for word in words]
    vowels = list('aeiou')
    vowel_count = 0
    for word in words:
        if len(word) == 8 and 's' not in word:
            for letter in words:
                if letter in vowels:
                    vowel_count += 1
        if vowel_count == 1:
            #print(word)
            return word


def main():
    dictionary = open('./dictionary.txt', 'r')
    print("part 1")
    #part1(dictionary)
    print("part 4")
    part4(dictionary)


main()

您可能应该将文件名作为参数传递给part4函数,然后创建一个新的file对象,因为当您遍历它一次时,它将停止返回新行。你知道吗

def main():
    dict_filename = 'dictionary.txt'
    print("part 4")
    part4(dict_filename)


def part1(dict_filename):
    vowels = 'aeiouy'
    vowelcount = 0
    dictionary = open(dict_filename,'r')
    for words in dictionary:
        words = words.lower()
        vowelcount = 0
        if len(words) == 8:
            if 's' not in words:
                for letters in words:
                    if letters in vowels:
                        vowelcount += 1
                if vowelcount == 1:
                    print(words)
    return words

def part4(dict_filename):
    dictionary = open(dict_filename,'r')
    naclcount = 0
    for words in dictionary:
        if 'nacl' in words:
            naclcount = naclcount + 1
    return naclcount

main()

另外,如果您希望能够将脚本作为导入的模块或独立的模块使用,则应该使用

if __name__ == '__main__':
    dict_filename = 'dictionary.txt'
    print("part 4")
    part4(dict_filename)

代替main函数

相关问题 更多 >