简体   繁体   English

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

[英]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.

相关问题 Python-如何匹配文本文件中多行中的特定单词/数字并将它们存储在单独的列表中 - Python - how to match specific words / digits from multiple lines in a text file and store them in separate lists 在特定字词之后查找所有字词,并将其替换为HTML代码 - Find all words after a specific word and replace it with HTML code 如何替换文件中的单词/数字 - How to replace words/digits in a file 如何使用 Python 将文本文件中仅出现一次的单词替换为其他单词? - How do you replace the words that are only appearing once with other word within a text file using Python? 如何在文本中查找特定单词并使用 python 计算它们? - How to find specific words in a text and count them using python? 有没有办法只替换文本文件中特定行和列中的特定单词? - Is there a way to only replace a specific word in a specefic line and collumn in text file? 正则表达式找到特定单词后的所有单词? - regex to find all words after specific word? 您有一个仅由数字组成的字符串。 您需要找出给定字符串开头有多少个零数字 ("0") - You have a string that consist only of digits. You need to find how many zero digits ("0") are at the beginning of the given string 如何用另一个词替换文本中的某些词 - How to replace some words in a text with another word 查找模式的所有匹配项并将其替换为文本 - Find all matches of a pattern and replace them in a text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM