如何分为两个功能?

时间:2014-11-07 00:17:37

标签: python

对于python中的基本计算机科学课,我们正在编写一个读取文件的程序,将文件翻译成pig latin并将翻译写入新文件,并计算翻译的行数和单词数。

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

1 个答案:

答案 0 :(得分:0)

好吧,因为这是一个家庭作业,我不会写代码。

看起来你的关键逻辑在于最内在的for-loop,你可以在其中找到一个单词并对其进行pig_latinify。

之后,您只需要一个映射器函数,用于将源的每个单词映射到文本的猪语言版本。此功能还可以计算行数。

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

这是我要做的:

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