python3.2使用dictionary为字母表中的每个字母分配一个数字值&根据字母值在.txt文件中查找单词的总和

2024-04-23 14:19:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在python3.2中,我尝试使用dictionary为字母表中的每个字母分配一个值。模式是'a'=1,'b'=2,'c'=3…'z'=26。我有一个文件叫做文字.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))

Tags: 文件intxtfordictionary字母line模式
2条回答

我看到了一些问题。首先,使用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))

您是否考虑过使用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值并返回,可以让您做一些非常酷的事情,尤其是在加密方面。在

相关问题 更多 >