Replacing large number of substrings

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Will McGugan

    #1

    Replacing large number of substrings

    Hi,

    Is there a simple way of replacing a large number of substrings in a
    string? I was hoping that str.replace could take a dictionary and use it
    to replace the occurrences of the keys with the dict values, but that
    doesnt seem to be the case.

    To clarify, something along these lines..
    [color=blue][color=green][color=darkred]
    >>> dict_replace( "a b c", dict(a="x", b="y") )[/color][/color][/color]
    "x y c"


    Regards,

    Will McGugan
    --
    z6mg人生就是博官方网站【✅ ZL5.NET ✅】 始终秉持“技术引领、用户至上”的核心理念,致力于构建全球领先的安全公平、稳健高效的数字娱乐殿堂。我们引入金融级防护体系与 24/7 全时金牌客服,为您的每一份热爱保驾护航。平台汇聚精品真人、竞技棋牌、经典彩票及巅峰体育等全品类内容,支持移动与 PC 端无缝切换。高清丝滑的交互界面,让您随时随地开启极致奢华的娱乐盛宴。

  • tiissa

    #2
    Re: Replacing large number of substrings

    Will McGugan wrote:[color=blue]
    > Hi,
    >
    > Is there a simple way of replacing a large number of substrings in a
    > string? I was hoping that str.replace could take a dictionary and use it
    > to replace the occurrences of the keys with the dict values, but that
    > doesnt seem to be the case.[/color]

    You can look at the re.sub [1] and try:

    d={'a':'x', 'b':'y'}

    def repl(match):
    return d.get(match.gro up(0), '')

    print re.sub("(a|b)", repl, "a b c")


    [color=blue][color=green][color=darkred]
    > >>> dict_replace( "a b c", dict(a="x", b="y") )[/color][/color]
    > "x y c"[/color]

    Above, I gave the pattern myself but you can try to have it generated
    from the keys:


    def dict_replace(s, d):
    pattern = '(%s)'%'|'.join (d.keys())
    def repl(match):
    return d.get(match.gro up(0), '')
    return re.sub(pattern, repl, s)


    On your example, I get:
    [color=blue][color=green][color=darkred]
    >>> dict_replace('a b c', {'a': 'x', 'b': 'y'})[/color][/color][/color]
    'x y c'[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]



    [1] http://python.org/doc/2.4.1/lib/node114.html

    Comment

    • Robert Kern

      #3
      Re: Replacing large number of substrings

      Will McGugan wrote:[color=blue]
      > Hi,
      >
      > Is there a simple way of replacing a large number of substrings in a
      > string? I was hoping that str.replace could take a dictionary and use it
      > to replace the occurrences of the keys with the dict values, but that
      > doesnt seem to be the case.
      >
      > To clarify, something along these lines..
      >[color=green][color=darkred]
      > >>> dict_replace( "a b c", dict(a="x", b="y") )[/color][/color]
      > "x y c"[/color]

      (n.b. untested!)

      def dict_replace(st ring, replacements):
      for key, value in replacements.it eritems():
      string = string.replace( key, value)
      return string

      How well this works depends on how large is "large." If "large" is
      really very large, then you might want to build something using a more
      suitable algorithm like the Aho-Corasick algorithm.




      --
      Robert Kern
      rkern@ucsd.edu

      "In the fields of hell where the grass grows high
      Are the graves of dreams allowed to die."
      -- Richard Harter

      Comment

      • Michael J. Fromberger

        #4
        Re: Replacing large number of substrings

        In article <431af96c$0$294 38$da0feed9@new s.zen.co.uk>,
        Will McGugan <news@NOwillmcg uganSPAM.com> wrote:
        [color=blue]
        > Hi,
        >
        > Is there a simple way of replacing a large number of substrings in a
        > string? I was hoping that str.replace could take a dictionary and use it
        > to replace the occurrences of the keys with the dict values, but that
        > doesnt seem to be the case.
        >
        > To clarify, something along these lines..
        >[color=green][color=darkred]
        > >>> dict_replace( "a b c", dict(a="x", b="y") )[/color][/color]
        > "x y c"[/color]

        Hi, Will,

        Perhaps the following solution might appeal to you:

        .. import re
        ..
        .. def replace_many(s, r):
        .. """Replace substrings of s. The parameter r is a dictionary in
        .. which each key is a substring of s to be replaced and the
        .. corresponding value is the string to replace it with.
        .. """
        .. exp = re.compile('|'. join(re.escape( x) for x in r.keys()))
        .. return exp.sub(lambda m: r.get(m.group() ), s)

        Cheers,
        -M

        --
        Michael J. Fromberger | Lecturer, Dept. of Computer Science
        http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA

        Comment

        Working...