文章中的字符成本

时间:2015-05-17 05:36:34

标签: python function python-3.x

此代码应该读取两个文件并计算其所有字符的潜在成本。带成本的文件(lettercosts.txt)如下所示:

  • a 1
  • b 3
  • c 2 等...

在这里,我试图让这一切都有效,但到目前为止,这一切都没有成功。 任何提示代码的问题在哪里?

def generate_cost_dict():
    letter_costs_dict = {}
    file = open("lettercosts.txt")
    with open("lettercosts.txt") as file:
       letter_cost_dict = {letter: int(cost)
                  for letter, cost in map(str.split, file)}
    return letter_costs_dict

def calculate_cost(article, lc_dict):

    with open("news1.txt") as x:
        for char in x.read():
            return sum(letter_cost_dict.get(char, 0)
    with open("news2.txt") as y:
        for char in y.read():
            return sum(letter_cost_dict.get(char, 0)              

def main():
    # Generating the mapping from letters to their USD costs
    lc_dict = generate_cost_dict()

    # Calculating the costs of the sample articles
    x = calculate_cost( "news1.txt", lc_dict )
    y = calculate_cost( "news2.txt", lc_dict )

    print("news1.txt costs",x,"USD.")
    print("news2.txt costs",y,"USD.")


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

使代码运行的最小变更集如下所示:

def generate_cost_dict():
    letter_costs_dict = {}
    file = open("lettercosts.txt")
    with open("lettercosts.txt") as file:
       letter_cost_dict = {letter: int(cost)
                  for letter, cost in map(str.split, file)}
    return letter_costs_dict

def calculate_cost(article, lc_dict):

    with open(article) as x:
        accum = 0
        for char in x.read():
            accum += lc_dict.get(char, 0)
        return accum           

def main():
    # Generating the mapping from letters to their USD costs
    lc_dict = generate_cost_dict()

    # Calculating the costs of the sample articles
    x = calculate_cost( "news1.txt", lc_dict )
    y = calculate_cost( "news2.txt", lc_dict )

    print("news1.txt costs",x,"USD.")
    print("news2.txt costs",y,"USD.")


if __name__ == '__main__':
    main()

虽然可能是最小代码:

with open('lettercosts.txt') as f:
    LC_DICT = {lett:int(cost) for line in f for lett,cost in [line.split()]}

def calculate_cost(article):
    with open(article) as f:
        return sum(LC_DICT.get(ch, 0) for line in f for ch in line)

x_cost = calculate_cost("news1.txt")
y_cost = calculate_cost("news2.txt")