Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Explanation here:
- ROMANIAN: https://neculaifantanaru.com/python-inverseaza-literele-din-cuvinte-ca-si-cand-cuvintele-s-ar-vedea-in-oglinda.html
- ENGLISH: https://neculaifantanaru.com/en/python-invert-the-letters-in-the-words-as-if-the-words-were-seen-in-the-mirror.html
- import re
- def read_text_from_file(file_path):
- """
- This function returns the contents of a file.
- """
- with open(file_path, 'r') as f:
- text = f.read()
- return text
- def write_to_file(text, file_path):
- """
- This function writes text to a file.
- text: the text you want to write
- """
- with open(file_path, 'w') as f:
- f.write(text)
- def reverse_words(file_path):
- """
- This function inverts all words in a file.
- """
- text = read_text_from_file(file_path)
- words = set(re.findall(r'[A-Za-z0-9\-\']+', text))
- for word in words:
- reversed_word = ''.join(reversed(word))
- text = text.replace(word, reversed_word)
- # we write the modified text in the file !!! attention, the content is overwritten !!!
- write_to_file(text, file_path)
- if __name__ == '__main__':
- # the path of your file
- file_path = 'd:\Exercises\1'
- reverse_words(file_path)
Add Comment
Please, Sign In to add comment