1

在 python 3.2 中,我试图使用字典为字母表中的每个字母分配一个值。模式是'a'=1,'b'=2,'c'=3…'z'=26。我有一个名为 words.txt 的文件,在这个文件中有一长串单词。单词以大写字母开头,但是,我的值仅针对小写字母定义。无论如何,当单词转换为小写时,我必须为每个单词分配一个与其字母值的总和相对应的值。我也知道如何找出列表中有多少单词的总值是 137 的整数倍?我也很困惑如何让 python 引用 .txt 文件。

欢迎任何帮助!谢谢你!

这是我到目前为止的代码:

d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':21,'w':23,'x':24,'y':25,'z':26}

find = open("words.txt")
[x.lower() for x in ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def num_multiple():  

  for line in find:
    if line.find("word % 137 == 0") == -1:
    return line
   else:
        word = line.strip()

print(num_multiple)
print(len(num_multiple))
4

2 回答 2

1

好吧,我在这里看到了一些问题。首先,您使用find的是查找文字字符串"word % 137 == 0"的结果,而不是计算的结果。

这里有一些东西可以简化你的代码:

values_of_words = [] # all the values for words

with open('words.txt') as the_file:
   for word in the_file:
       word = word.strip() # removes \n from the word
       values = [] # we will store letter values for each word
       for letter in word:
          # convert each letter to lowercase
          letter_lower = letter.lower()

          # find the score and add it to values
          values.append(d[letter_lower])

       # For each word, add up the values for each letter
       # and store them in the list
       values_of_words.append(sum(values))

count = 0
for value in values_of_words:
    if value % 137 == 0:
       count += 1

print("Number of words with values that are multiple of 137: {}".format(count))
于 2013-03-24T05:34:02.457 回答
0

您是否考虑过使用 ord() 和 chr() 函数来获取字母的 ASCII 值?

with open('words.txt')as word_file:
    high_score = 0
    for word in word_file:
        word = word.strip()
    value = 0
    for letter in word:
        value += ord(letter) % 97
    if value % 137 == 0:
        high_score += 1
    print('Number of words with values that are a multiple of 137 {}'.format(high_score))

我意识到这与您之前的答案没有什么不同,但是如果您的字典非常大,它可能会降低内存成本。此外,能够将字符转换为 ASCII 值并返回可以让您做一些非常酷的事情,尤其是在密码学方面。

于 2013-03-24T08:54:18.243 回答