473,378 Members | 1,360 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Searching and replacing text ?

Hi,

I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.

For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -Hotmail]]

I've to replace it with
[http://www.hotmail.com Hotmail]

I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')

p.sub('[',txt)
q.sub('\b',txt)

Give that I don't have very strong RegEX background, this doesn't look
very elegant. Is there some other way I can accomplish the same thing?
Moreover, please note that I'm using 'p' and 'q' for two regex and
then calling 'sub()' on both p and q. Can't I just do that by
employing one RegEx and then calling sub() only once?

Please enlighten me. Thanks in advance.

Jun 27 '08 #1
3 1201
En Fri, 02 May 2008 15:51:42 -0300, Oltmans <ro**********@gmail.com>
escribió:
Hi,

I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.

For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -Hotmail]]

I've to replace it with
[http://www.hotmail.com Hotmail]

I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')

p.sub('[',txt)
q.sub('\b',txt)
Is it a constant text? Then use the replace method of string objects: no
re is needed.

text = "This is [[http://www.hotmail.com -Hotmail]] some text"
print text.replace("[[http://www.hotmail.com -Hotmail]]",
"[http://www.hotmail.com Hotmail]")
output: This is [http://www.hotmail.com Hotmail] some text

Or, do you want to find '[[' followed by some word followed by ' -'
followed by another word followed by ']]'?

r = re.compile(r'\[\[(.+?)\s*->\s*(.+?)\]\]')
print r.sub(r'[\1 \2]', text)
(same output as above)

() in the regular expression indicate groups, that you can reference as \1
\2 in the replacement string.

--
Gabriel Genellina

Jun 27 '08 #2
Oltmans wrote:
Hi,

I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.

For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -Hotmail]]

I've to replace it with
[http://www.hotmail.com Hotmail]

I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')

p.sub('[',txt)
q.sub('\b',txt)

Give that I don't have very strong RegEX background, this doesn't look
very elegant. Is there some other way I can accomplish the same thing?
Moreover, please note that I'm using 'p' and 'q' for two regex and
then calling 'sub()' on both p and q. Can't I just do that by
employing one RegEx and then calling sub() only once?

Please enlighten me. Thanks in advance.
If you really want to replace EVERY occurrence, no regexes are needed.
I'd do something like (not tested):

fp=open(inputfilename, 'r')
contents=fp.read()
fp.close()
parts=contents.split('[[http://www.hotmail.com -Hotmail]]')
newcontents='[http://www.hotmail.com Hotmail]'.join(parts)
fp=open(outputfilename, 'w')
fp.write(newcontents)
fp.close()

-Larry
Jun 27 '08 #3
If you know that, for instance, every occurrence of '[[' needs to be
replaced with ']]', then it is much faster to use regular string
methods. If you have the text stored in the variable foo:

foo = foo.replace('[[', '[').replace(']]', ']').replace('->', '')

If you need to recognize the actual pattern, use REs:

regex = re.compile(r'\[\[(.+?) -(.+?)\]\]')
regex.sub(r'[\1 \2]', foo)
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Christopher R. Barry | last post by:
I need to search and replace multiple words in one pass of an input stream or string. For example, given the input: "The quick brown fox jumped over the lazy dog's back" and given the...
7
by: Rob Meade | last post by:
Hi all, Been a long time since I've been here... /me waves to all.. Ok - my conundrum.. I have a form where a user can enter text and BB codes...for example:
2
by: thehuby | last post by:
Isn't inserting good data and getting it out of a db a pain in the a$$? I am going to be using the Markdown text to HTML parser (http://daringfireball.net/projects/markdown/dingus) for creating...
8
by: Gordon Knote | last post by:
Hi can anyone tell me what's the best way to search in binary content? Best if someone could post or link me to some source code (in C/C++). The search should be as fast as possible and it would...
12
by: Adam J. Schaff | last post by:
I am writing a quick program to edit a binary file that contains file paths (amongst other things). If I look at the files in notepad, they look like: ...
1
Corster
by: Corster | last post by:
I went through a great deal of hassle to figure this out for myself, but now it is complete, I would like to share it with the world! I know afew other people have had trouble with FindFirst and...
2
by: gsuns82 | last post by:
Hi all, I have to replace accented characters from a input string with normal plain text.I have coded as follows. String input = "ÄÀÁÂÃ"; input=...
4
by: wildman | last post by:
RE: Replacing Text without changing case?? This code works great, but case has to be exact. Research.Text = Research.Text.Replace(textboxSearch.Text, "<b>" + textboxSearch.Text + "</b>") ...
1
by: duncanm817 | last post by:
hi, I require some assistance in understanding how to accomplish replacing a particular hex value in a binary file on aix. in a binary file I need to find the following combination: 5A 00 10...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.