|
| 1 | +# exercise 9.1.2 from unit 9 |
| 2 | +''' |
| 3 | +Write a program that receives from the user: |
| 4 | +
|
| 5 | +Path to text file (string) |
| 6 | +Name of one of the operations: rev, sort or last (string) |
| 7 | +The file we return is passed as an argument containing lines of lowercase word sequences separated by a single space. |
| 8 | +
|
| 9 | +According to the name of the action received from the user, the program performs: |
| 10 | +
|
| 11 | +sort - the program prints all the words in the transferred file as a sorted list in alphabetical order, without duplicates. |
| 12 | +rev - the program prints the characters in each line in the file in reverse order, i.e. from the end to the beginning. |
| 13 | +last - the program receives another parameter from the user which is an integer (n), and prints the last n lines in the file (assume that the number is positive and less than or equal to the number of lines in the file). |
| 14 | +An example of an input file and lectures of the program |
| 15 | +A file called sampleFile.txt: |
| 16 | +
|
| 17 | +i believe i can fly i believe i can touch the sky |
| 18 | +I think about it every night and day spread my wings and fly away |
| 19 | +Run the program on the file sampleFile.txt: |
| 20 | +
|
| 21 | +>>> Enter a file path: c:\sampleFile.txt |
| 22 | +>>> Enter a task: sort |
| 23 | +['about', 'and', 'away', 'believe', 'can', 'day', 'every', 'fly', 'i', 'it', 'my', 'night', ' sky', 'spread', 'the', 'think', 'touch', 'wings'] |
| 24 | +>>> Enter a file path: c:\sampleFile.txt |
| 25 | +>>> Enter a task: rev |
| 26 | +yks eht hcuot nac i eveileb i ylf nac i eveileb i |
| 27 | +yawa ylf dna sgniw ym daerps yad dna thgin yreve ti tuoba kniht i |
| 28 | +>>> Enter a file path: c:\sampleFile.txt |
| 29 | +>>> Enter a task: last |
| 30 | +>>> Enter a number: 1 |
| 31 | +I think about it every night and day spread my wings and fly away |
| 32 | +''' |
| 33 | + |
| 34 | +def main(): |
| 35 | + file_path = input("Enter a file path: ") |
| 36 | + task = input("Enter a task: ") |
| 37 | + with open(file_path, 'r') as f: |
| 38 | + lines = f.readlines() |
| 39 | + if task == 'sort': |
| 40 | + words = sorted(set(line.split() for line in lines)) |
| 41 | + print(words) |
| 42 | + elif task == 'rev': |
| 43 | + reversed_lines = [line[::-1] for line in lines] |
| 44 | + print(reversed_lines) |
| 45 | + elif task == 'last': |
| 46 | + n = int(input("Enter a number: ")) |
| 47 | + print(lines[-n:]) |
| 48 | + |
| 49 | +main() |
0 commit comments