【问题标题】:How to replace multiple words with one word in python? [duplicate]如何在python中用一个单词替换多个单词? [复制]
【发布时间】:2015-09-11 04:03:44
【问题描述】:

我有一些可能包含缩写或全名的字符串,我想将它们全部替换为单词的相同变体。

例如,

“8 场演出”, “8 GB”,以及 “8GB” 应该全部更改为 “8 GB”

最好的方法是什么?对他们每个人都有单独的替换吗?

此外,我正在尝试对多个单词(即兆字节、太字节)执行此操作,是否每个单词都需要不同的替换,或者有没有办法将它们全部放在一起?

【问题讨论】:

    标签: python string replace


    【解决方案1】:

    一个简单的re.sub 会为您解决问题。

    >>> import re
    >>> s = 'gigabytes, foo gigs; foo gbs'
    >>> re.sub('(gigabytes|gigs|gbs)','gigabytes',s)
    'gigabytes, foo gigabytes; foo gigabytes'
    

    【讨论】:

      【解决方案2】:
      >>> import re
      >>> re.sub(r'(\d+) (gigs|gigabytes|gbs)', r'\1 gigabytes', str)
      

      对于多个替换,诀窍是使用可调用(在本例中为 lambda 函数)作为替换:

      >>> gb='gigabytes'
      >>> mb='megabytes'
      >>> subs={'gigs': gb, 'gigabytes': gb, 'gbs': gb, 'mbs': mb, ...}
      >>> str='there are 2048 mbs in 2 gigs'
      >>> re.sub(r'(\d+) ({})'.format('|'.join(subs.keys())), \
              lambda x: '{} {}'.format(x.group(1), subs[x.group(2)]), str)
      'there are 2048 megabytes in 2 gigabytes'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多