Is this your homework?
#!/usr/bin/env python3 from string import ascii_uppercase as upper # creating a mapping for A-Z : 1-26 # access is very fast mapping = {char: value for (char, value) in zip(upper, range(1, len(upper) + 1))} # {'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': 22, # 'W': 23, # 'X': 24, # 'Y': 25, # 'Z': 26} # functional approach def word_sum(word): return sum(map(lambda x: mapping.get(x.upper(), 0), word)) # word_sum('!-.$%"§A') # should return 1 # better to understand def word_sum(word): result = 0 for char in word: # make char uppercase, return 0 if char not in mapping # https://docs.python.org/3/library/stdtypes.html#mapping-types-dict value = mapping.get(char.upper(), 0) result += value return result def analyse_and_write(file_in): # using a context manager # leaving the context closes the file :-) with open(file_in) as fd: # this iterates line for line over the text. for line in fd: # calculates the sum and converts the integer into a string s = word_sum(line) if not s: #when s == 0, skip it continue s = str(s) # we need the number as string to write it into the textfile file_out = s + '.txt' # here a context manager again to write the file with open(file_out, 'a') as out: # 'a' is for append. If the file does not exists, # it will be created. If the file exists, it will append. out.write(line) if __name__ == '__main__': print('Staring program') analyse_and_write('WordList100000Plus.txt') print('Done')
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!