繁体   English   中英

如何在仅包含数字的文本文件中查找所有单词并将其替换为特定单词

[英]How to find all words in text file which consist only of digits and replace them with a specific word

如何在仅由数字组成的文本文件中查找所有单词(两边用空格分隔)并用特定单词替换它们。 如果我想将一个词替换为一个词,我确实喜欢这样做,但是数字词呢? 它们可以由不同的长度组成。 谢谢。

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\".")

使用正则表达式,最容易与 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

链接到此正则表达式的逐步分析: https://regex101.com/r/d7rljs/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM