簡體   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