Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Using Regex to split text into words, preserving all punctuation
- import re
- list_of_long_texts = ["Hello Fred, what time is it?", "Too early, for me!"]
- # mydict contains words which are to be replaced in the text
- mydict = {"time": "hour", "early": "late", "me": "you", "Fred": "Jim"}
- for text in list_of_long_texts:
- outline = ""
- arr = re.split('(\W)', text) # Create a list containing every word and separator
- for w in arr:
- if w in mydict: # If word exists in the dictionary ...
- w = mydict[w] # ... replace it with the dictionary entry
- outline += w # Append word or separator onto output line
- print(outline)
- # Result:-
- # Hello Jim, what hour is it?
- # Too late, for you!
Add Comment
Please, Sign In to add comment