non-uniform string substituion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Horacius ReX

    non-uniform string substituion

    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.
  • Steve Holden

    #2
    Re: non-uniform string substituion

    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.ha nda" you could say

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

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

    Comment

    • 7stud

      #3
      Re: non-uniform string substituion

      On Feb 13, 4:03 pm, Horacius ReX <horacius....@g mail.comwrote:
      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(li ne)

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

      Comment

      Working...