[英]How to find all words in text file which consist only of digits and replace them with a specific word
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\".")
Use regex, most easily available with Python's re
module:使用正则表达式,最容易与 Python 的re
模块一起使用:
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链接到此正则表达式的逐步分析: https://regex101.com/r/d7rljs/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.