[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

non-uniform string substituion

Horacius ReX

2/13/2008 11:03:00 PM

Hi,

I have a file with a lot of the following ocurrences:

denmark.handa.1-10
denmark.handa.1-12344
denmark.handa.1-4
denmark.handa.1-56

....

distributed randomly in a file. I need to convert each of this
ocurrences to:

denmark.handa.1-10_1
denmark.handa.1-12344_1
denmark.handa.1-4_1
denmark.handa.1-56_1

so basically I add "_1" at the end of each ocurrence.

I thought about using sed, but as each "root" is different I have no
clue how to go through this.

Any suggestion ?

Thanks in advance.
2 Answers

Steve Holden

2/14/2008 1:25:00 AM

0

Horacius ReX wrote:
> Hi,
>
> I have a file with a lot of the following ocurrences:
>
> denmark.handa.1-10
> denmark.handa.1-12344
> denmark.handa.1-4
> denmark.handa.1-56
>
> ...
>
> distributed randomly in a file. I need to convert each of this
> ocurrences to:
>
> denmark.handa.1-10_1
> denmark.handa.1-12344_1
> denmark.handa.1-4_1
> denmark.handa.1-56_1
>
> so basically I add "_1" at the end of each ocurrence.
>
> I thought about using sed, but as each "root" is different I have no
> clue how to go through this.
>
> Any suggestion ?
>
> Thanks in advance.

First you have to tell us what characterizes the lines you want to
process. For example, if the only requirement is that they begin with
"denmark.handa" you could say

for line in sys.stdin:
if line.startswith("denmark.handa"):
line = line[:-1]+"_1\n"
sys.stdout.write(line)

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.hold...

7stud --

2/14/2008 3:37:00 AM

0

On Feb 13, 4:03 pm, Horacius ReX <horacius....@gmail.com> wrote:
> Hi,
>
> I have a file with a lot of the following ocurrences:
>
> denmark.handa.1-10
> denmark.handa.1-12344
> denmark.handa.1-4
> denmark.handa.1-56
>
> ...
>
> distributed randomly in a file. I need to convert each of this
> ocurrences to:
>
> denmark.handa.1-10_1
> denmark.handa.1-12344_1
> denmark.handa.1-4_1
> denmark.handa.1-56_1
>

Is each one of those a line in the file? Or are those words
distributed throughout the file? If each one is a line, try this:

import os

input = open('data.txt')
output = open('temp.txt', 'w')

for line in input:
if line.startswith('denmark.handa.'):
output.write('%s_1\n' % line.strip())
else:
output.write(line)

os.remove('data.txt')
os.rename('temp.txt', 'data.txt')