Python 如何划分为两个功能?

Python 如何划分为两个功能?,python,Python,对于python的基础计算机科学课程,我们正在编写一个程序,该程序读入一个文件,将该文件翻译成pig拉丁语,并将翻译写入一个新文件,并计算翻译的行数和单词数 file_path = raw_input("Enter a file pathway: ") f_input = file(file_path, "r") f_output = file("pig_output.txt","w") vowels = ("a","e","i","o","u","A","E","I","O","U")

对于python的基础计算机科学课程,我们正在编写一个程序,该程序读入一个文件,将该文件翻译成pig拉丁语,并将翻译写入一个新文件,并计算翻译的行数和单词数

file_path = raw_input("Enter a file pathway: ")
f_input = file(file_path, "r")
f_output = file("pig_output.txt","w")

vowels = ("a","e","i","o","u","A","E","I","O","U")


def piglat_trans():
    line_count = 0
    word_count = 0
    for line in f_input:
        words = line.split(" ")
        pig_line = ""
        line_count += 1
        for word in words:
            word = word.strip("\n")
            word_count += 1
            if word[0] in vowels:
                pig_word = word + "way"
            elif word[0] not in vowels and word[1] not in vowels and len(word)>1:
                pig_word = word [2:len(word)] + word[0] + word[1] + "ay"
            else:
                pig_word = word[1:len(word)] + word[0] + "ay"
            pig_line += pig_word + " "
        f_output.write(pig_line + "\n")
    print "Translation finished and written pig_output.txt"
    print "A total of " + str(line_count) + " lines were translated successfully."
    print "A total of " + str(word_count) + " words were translated successfully."


piglat_trans()

f_input.close()
f_output.close()
该程序运行良好,但我应该使行/字计数和打印部分与转换器本身的功能分离。我该怎么做

谢谢你的帮助! **编辑:另外,我在翻译时遇到空格和制表符的问题,它返回:

line 25, in piglat_trans if word[0] in vowels:
IndexError: string index out of range

既然这是一个家庭作业,我就不写代码了

看起来您的关键逻辑位于最内部的for循环中,在该循环中,您获取一个单词并将其拼音化

然后,您只需要一个映射器函数,将源代码中的每个单词映射到文本的拉丁版本。此函数还可以计算行数

并且,尝试使您的文件处理程序短命,并使用上下文管理器(
和Python中的
语句)

下面是我要做的:

def pigify(word):
    ....
    return pig

def pigify_text(text):
    ...
    pig_words = map(pigify, words)
    ...
    return (pig_text, word_count, line_count)

with open(infile) as f:
    text = f.read()

pig, wc, lc = pigify_text(text)

with open(outfield, "w") as f:
     f.write(pig)

print wc
print lc

对于最后一个错误,请考虑<代码> 'B'。拆分(“”)< /代码>将返回<代码> [a,',' b' ] < /代码>;您可能希望只使用
.split()
而不带参数。