python 3.2-使用字典为字母赋值并计算.txt文件中单词的字母总和
在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))
2 个回答
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值再转换回来,可以让你做一些很酷的事情,特别是在加密方面。
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))