Sometimes, we want to replace a string or word of a given paragraph by another string or word and we can do it by editing the paragraph by searching the word but when the length of the paragraph is too large then we feel tired after doing this. So, to overcome this problem we will learn how to do the same things in Python and also we will use the re module of Python to make it so easy.
有时,我们想用另一个字符串或单词替换给定段落的字符串或单词 ,我们可以通过搜索单词来编辑段落来实现,但是当段落的长度太大时,这样做后我们会感到疲倦。 因此,为克服此问题,我们将学习如何在Python中执行相同的操作,并且还将使用Python的re模块使其变得如此简单。
Python has an inbuilt re module which allows us to solve the various problems based on pattern matching and string manipulation. To understand the problem simply, let's take an example.
Python有一个内置的re模块 ,它使我们能够解决基于模式匹配和字符串操作的各种问题。 为了简单地理解问题,让我们举个例子。
Example:
例:
Input:
"These days, Engineers are struggling to get a job in a better company due
to the lack of experience and also due to the high competition.
Engineers have the only book knowledge but the company is expecting the
industrial experience in the Engineers for better productivity."
Replacing:
"Engineers"with "students"
Output:
"These days, students are struggling to get a job in a better company due
to the lack of experience and also due to the high competition.
Students have the only book knowledge but the company is expecting the
industrial experience in the students for better productivity."
Algorithm to solve the above problem
解决以上问题的算法
Import the re module in the program.
将re模块导入程序中。
Take paragraph as input also a word which uses to replace a special string.
将段落也作为输入来代替一个特殊的字符串作为输入。
Print the new paragraph which has replaced string.
打印已替换字符串的新段落。
Program:
程序:
# importing the module
import re
# string
paragraph='''These days, Engineers are struggling to get a job in a better
company due to the lack of experience and also due to the high competition.
Engineers have the only book knowledge but the company is expecting the
industrial experience in the Engineers for better productivity.'''
# replacing string
reg=re.compile('Engineers')
s=reg.sub("students",paragraph)
# printing the replaced string
print(s)
Output
输出量
These days, students are struggling to get a job in a better
company due to the lack of experience and also due to the high competition.
students have the only book knowledge but the company is expecting the
industrial experience in the students for better productivity.