Python根据传递的值在文件中查找单词

时间:2018-11-10 11:25:48

标签: python

我想创建一个简单的方法,程序将根据命令行中传递的值在文件中查找单词。

class Option():
    SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
                (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
    global LETTER_SCORES 
    LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
             for letter in letters.split()}

    def word_from_score(self,score):
        file = [line.rstrip('\n') for line in open('dictionary.txt', "r")]

例如,如果我运行python main.py -s 7,它将返回KOT。我知道如何创建argparse,但是在查找单词并将其添加到列表时遇到问题

[编辑] 我写了这样的东西:

def word_from_score(self,score):
    file = [line.rstrip('\n') for line in open('dictionary.txt', "r")]

    return [word for word in file if sum([LETTER_SCORES[letter] for letter in word ]) == score]

1 个答案:

答案 0 :(得分:0)

列表理解是您的朋友。要计算单词的分数:

nohup /voip/java/jdk1.8.0_71/bin/java -server  -Xss256k -Xms500m -Xmx500m -DServerName=`pwd`/application com.application

并过滤出所有匹配的单词:

def scoreOf(word):
    return sum( [ LETTER_SCORES[letter] for letter in word ] )

或者,如果您真的愿意,甚至可以将它们合并为一个单行:

def wordsWithScore(allWords, targetScore):
    return [ word for word in allWords if scoreOf(word) == targetScore ]