如何使用letter_score像代码中那样检查txt文件中word的最大值?

时间:2018-11-05 17:09:21

标签: python python-3.x

如何在Python中计算导入的txt文件中单词的值?我确实是这样做的,却不知道该如何计算单词的价值。

import itertools


letter_score = 
{

                'a' : 1, 'e' : 1, 'o' : 1,
               'i' : 1, 'n' : 1, 'r' : 1,
               'l' : 1, 't' : 1, 'l' : 1,
               's' : 1, 'n' : 1, 'd' : 2,
               'g' : 2, 'b' : 3, 'c' : 3,
               'm' : 3, 'p' : 3, 'f' : 4,
               'h' : 4, 'v' : 4, 'w' : 4,
               'y' : 4, 'k' : 5, 'j' : 8,
               'x' : 8, 'q' : 10, 'z' : 10 
}




def load_dict(path):
    words = "dictionary.txt"
    return words


fname = input('dictionary.txt')
num_words = 0

with open(fname, 'r') as f:
    for line in 'f':
        words = line.split()
        num_words += len(words)
print("Number of words:")
print(num_words)

2 个答案:

答案 0 :(得分:0)

您可以使用诸如list()之类的函数来创建字符列表,并使用诸如for之类的函数来迭代该列表并将值与字典进行比较。

答案 1 :(得分:0)

定义函数,计算单词的值,创建所有单词的列表,应用函数,然后找到最大值。值:

def word_value(word, dic):
    """calculate value of the word"""
    return sum([dic[char] for char in word])


def read_file(fname):
    num_words = 0
    all_words = []
    with open(fname, 'r') as f:
        for line in 'f':
            words = line.split()
            num_words += len(words)
            all_words.extend(words)
    return all_words, num_words

fname = input('dictionary.txt')
all_words, num_words = read_file(fname)

letter_score = {
            'a' : 1, 'e' : 1, 'o' : 1,
           'i' : 1, 'n' : 1, 'r' : 1,
           'l' : 1, 't' : 1, 'l' : 1,
           's' : 1, 'n' : 1, 'd' : 2,
           'g' : 2, 'b' : 3, 'c' : 3,
           'm' : 3, 'p' : 3, 'f' : 4,
           'h' : 4, 'v' : 4, 'w' : 4,
           'y' : 4, 'k' : 5, 'j' : 8,
           'x' : 8, 'q' : 10, 'z' : 10 }

all_words_values = [(word, word_value(word, letter_score)) for word in all_words]
# list of tuples [(word, value)]
max_word = max(all_words_values, key=lambda x: x[1])  # find maximum by value 
# max_word is smth like ("apple", 9)

希望有帮助!