Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Session 03 - Python for Forensics

The code here is to support the Session 03 lecture.

wordswap.py

import re

def replaceWords(text, wordType, userInput):
    pattern = r'\b' + wordType + r'\b'
    return re.sub(pattern, userInput, text)

def main():
    with open('wordswap.txt', 'r') as file:
        text = file.read()

    wordTypes = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']

    for wordType in wordTypes:
        userInput = input(f'Enter {wordType.lower()}: ')
        text = replaceWords(text, wordType, userInput)

    print(text)

    with open('wordswaped.txt', 'w') as file:
        file.write(text)

if __name__ == "__main__":
    main()
[ Last updated: Tuesday 13 February 2024 @ 13:40:05 +0000 // branch: master // commit: 5c34658 ]