Python文件操作

如果把字母 a 计为 1b 计为 2c 计为 3……z 计为 26,那么:

  • knowledge = 96
  • hardwork = 98
  • attitude = 100

所以结论是:

  • 知识( knowledge )与勤奋(hardwork)固然都很重要;
  • 但是,决定成败的却是态度(attitude)!

貌似说的有道理,但可以找出英文单词中字母累加值等于100的单词。

可以在https://github.com/dwyl/english-words上下载words_alpha.txt文件,

def sum_of_word(word):
    sum = 0
    for char in word:
        sum += ord(char)-96    # ord()将字符转换为数值,a为97,减去96即为1
    return sum

with open('words_alpha.txt','r') as file:
    for word in file.readlines():
        if sum_of_word(word.strip()) == 100:   #strip()方法用来去除换行符
            print(word)
    
原文地址:https://www.cnblogs.com/augustine0654/p/14660658.html