How to find all words (separated with spaces from both sides) in text file which consist only of digits and replace them with a specific word. I do like this if I want to replace a word to a word, but how about digit words? They can consist of different lengths. Thanks.
fin = open("tekstas.txt", "rt") with open('tekstas.txt') as f: if ' ir ' in f.read(): fout = open("naujasTekstas.txt", "wt") for line in fin: fout.write(line.replace(' '', ' skaičius ')) fin.close() fout.close() f.close() else: print("Nėra žodžio "ir".")
Advertisement
Answer
Use regex, most easily available with Python’s re
module:
import re text = "word another word 121434" pattern = '[0-9]+' print(re.sub(pattern=pattern, repl='replacement', string=text)) # word another word replacement
Link to step by step analysis of this regex: https://regex101.com/r/d7rljs/1