+ 2

How to read an integer from a file and write back it in words to the file in python?

Foe example it reads 123 from file it should write one hundred and twenty three to file

13th Jul 2019, 12:31 PM
j s
j s - avatar
2 ответов
0
''' Created on Aug 23, 2019 @author: Anshap This program converts numbers (in range 0 .. 999) to words ''' def main(): less20 = ["null", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] less100 = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] f1 = open('numbers.txt') f2 = open('words.txt', 'w') f2.write("Output file converts numbers to words\n") for line in f1.readlines(): line = line.lstrip(); line = line.rstrip(); if line.isdigit(): if int(line) < 20: for i in range(20): if line == str(i): print(line + " " + less20[i], end='\n') f2.write(line + " " + less20[i] + '\n') break elif int(line) in range(20, 100): a = int(line) // 10 b = int(line) % 10 if b == 0: print(line + " " + less100[a-2], end='\n') f2.write(line + " " + less100[a-2] + '\n') elif b > 0: print(line + " " + less100[a-2] + "-" + less20[b], end='\n') f2.write(line + " " + less100[a-2] + "-" + less20[b] + '\n')
23rd Aug 2019, 3:55 PM
anshap
anshap - avatar
0
elif int(line) in range(100, 1000): c = int(line) // 100 d = int(line) % 100 if d == 0: print(line + " " + less20[c] + " hundred ", end='\n') f2.write(line + " " + less20[c] + " hundred" + '\n') elif d > 0: if d < 20: for i in range(20): if str(d) == str(i): print(line + " " + less20[c] + " hundred and " + less20[i], end='\n') f2.write(line + " " + less20[c] + " hundred and " + less20[i] + '\n') break elif d >= 20: a = d // 10 b = d % 10 if b == 0: print(line + " " + less20[c] + " hundred and " + less100[a-2], end='\n') f2.write(line + " " + less20[c] + " hundred and " + less100[a-2] + '\n') elif b > 0: print(line + " " + less20[c] + " hundred and " + less100[a-2] + "-" + less20[b], end='\n') f2.write(line + " " + less20[c] + " hundred and " + less100[a-2] + '\n') print("Output file is created.", end='\n') f1.close() f2.close() if __name__ == '__main__':main()
23rd Aug 2019, 3:55 PM
anshap
anshap - avatar