【问题标题】:How to replace a Word in DF Column with another Word using Python -without including the substring如何使用 Python 将 DF 列中的单词替换为另一个单词 - 不包括子字符串
【发布时间】:2020-08-12 14:41:37
【问题描述】:

我正在尝试在 Python 中实现 SAS TRANWRD 函数的功能,以将 'WORD' 替换为另一个 'WORD'。

我曾尝试使用 Python 中可用的 str.replacereplace 方法,但这些方法除了替换词。

代码:

DICT1 = {'NZ':'NEW ZEALAND'}

for k,v in DICT1.items():
    df['COL1'] = df['COL1'].str.replace(k,v)

例如:

NZ COMPANY LIMITED --> NEW ZEALAND COMPANY LIMITED - *(Expected)*

GONZU ENTERPRISE --> GONEW ZEALANDU ENTERPRISE - *(Unexpected)*

在 SAS 中,这个问题得到了注意,因为 TRANWRD 函数只在找到空间边界后替换单词。

有人可以帮助如何在 Python 中实现类似的功能吗?

【问题讨论】:

    标签: python sas code-conversion


    【解决方案1】:

    使用利用词边界元字符\b的正则表达式搜索模式

    例子:

    import re
    
    seekword = "Bob"
    rplcword = "Bubba"
    
    phrase = "Hello there Bob"
    phrasex = re.sub(r"\b"+seekword+r"\b", rplcword, phrase)
    
    print (phrasex)
    

    示例 2:

    循环多个短语和替换

    import re
    
    PHRASES = \
    [ 'Bill is from AU' \
    , 'Bob is from NZ' \
    , 'Bobby visited NZA' \
    ]
    
    WORDMAPS = \
    { 'Bob': 'Bubba' \
    , 'NZ': 'NEW ZEALAND'
    }
    
    for index, phrase in enumerate(PHRASES):
        
        phrasex = phrase
        
        for k,v in WORDMAPS.items():
            phrasex = re.sub(r"\b"+k+r"\b", v, phrasex)
            
        PHRASES[index] = phrasex
            
    print (PHRASES)
    

    【讨论】:

    • 感谢您的回复。有没有办法使用 Python Dictionary 实现您的建议?我有一长串“seekword”及其对应的“rplcword”
    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多