nicuf

invert the letters in the words

Nov 8th, 2021 (edited)
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. Explanation here:
  2.  
  3. ROMANIAN: https://neculaifantanaru.com/python-inverseaza-literele-din-cuvinte-ca-si-cand-cuvintele-s-ar-vedea-in-oglinda.html
  4. ENGLISH: https://neculaifantanaru.com/en/python-invert-the-letters-in-the-words-as-if-the-words-were-seen-in-the-mirror.html
  5.  
  6.  
  7. import re
  8.  
  9. def read_text_from_file(file_path):
  10.     """
  11.    This function returns the contents of a file.
  12.    """
  13.     with open(file_path, 'r') as f:
  14.         text = f.read()
  15.         return text
  16.  
  17. def write_to_file(text, file_path):
  18.     """
  19.    This function writes text to a file.
  20.    text: the text you want to write
  21.    """
  22.     with open(file_path, 'w') as f:
  23.         f.write(text)
  24.  
  25. def reverse_words(file_path):
  26.     """
  27.    This function inverts all words in a file.
  28.    """
  29.    
  30.     text = read_text_from_file(file_path)
  31.     words = set(re.findall(r'[A-Za-z0-9\-\']+', text))
  32.     for word in words:
  33.         reversed_word = ''.join(reversed(word))
  34.         text = text.replace(word, reversed_word)
  35.     # we write the modified text in the file !!! attention, the content is overwritten !!!
  36.     write_to_file(text, file_path)
  37.  
  38. if __name__ == '__main__':
  39.     # the path of your file
  40.     file_path = 'd:\Exercises\1'  
  41.     reverse_words(file_path)
Add Comment
Please, Sign In to add comment