0
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
4

2 回答 2

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

于 2013-03-18T03:54:44.737 回答
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()
于 2013-03-18T04:02:14.990 回答