在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))
答案 0 :(得分: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))
答案 1 :(得分: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值并返回可以使您做一些非常酷的事情,尤其是在加密中。