此代码未显示正确答案

时间:2013-03-18 03:47:15

标签: python file-io python-3.x

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

2 个答案:

答案 0 :(得分:1)

您应该将文件名作为参数传递给part4函数,然后创建一个新的文件对象,因为当您迭代一次时,它将停止返回新行。

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功能

答案 1 :(得分:0)

你能粘贴你的另一个功能吗?除非你展示另一个功能,否则问题不明确。

从我的问题和代码推断出来的。我修改了(清理)你的代码。看看它是否有帮助。

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