【问题标题】:Is there a shorter way to replace words in a string? [duplicate]有没有更短的方法来替换字符串中的单词? [复制]
【发布时间】:2020-04-16 03:36:45
【问题描述】:

这是我的任务

journey = """Just a small tone girl
Leaving in a lonely whirl
She took the midnight tray going anywhere
Just a seedy boy
Bored and raised in South Detroit or something
He took the midnight tray going anywhere"""

毛。好的,对于这个练习,你的工作是使用 Python 的字符串替换方法来修复这个字符串并将新版本打印到控制台。

这就是我所做的

journey = """ just a small tone girl
Leaving in a lonely whirl
she took a midnight tray going anywhere
Just a seedy boy
bored and raised in south detroit or something
He took the midnight tray going anywhere"""

journeyEdit = journey.replace("tone" , 
"town").replace("tray","train").replace("seedy","city").replace("Leaving", 
"living").replace("bored","born").replace("whirl","world").replace("or 
something", " ")

print (journeyEdit)

【问题讨论】:

  • 有更短的方法吗?
  • 嗯,这有点短,但事实是,它效率不高。你可以要求一种我认为你可以做到的有效方法。
  • 使用字典? y = d.get(x, x)

标签: python str-replace


【解决方案1】:

可能比你给的要长;-)。

How to replace multiple substrings of a string?

import re

journey = """ just a small tone girl Leaving in a lonely whirl she took a 
midnight tray going anywhere Just a seedy boy bored and raised in south 
detroit or something He took the midnight tray going anywhere"""

rep = {"tone": "town",
       "tray": "train",
       "seedy":"city",
       "Leaving": "living",
       "bored":"born",
       "whirl":"world",
       "or something": " "}

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())

# Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))

journeyEdit = pattern.sub(lambda m: rep[re.escape(m.group(0))], journey)

print(journeyEdit)

【讨论】:

    【解决方案2】:

    这是从文本中替换单词的示例方法。你可以使用 python re 包。

    请找到以下代码作为指导。

    import re
    journey = """ just a small tone girl Leaving in a lonely whirl she took a 
    midnight tray going anywhere Just a seedy boy bored and raised in south 
    detroit or something He took the midnight tray going anywhere"""
    # define desired replacements here
    
    journeydict = {"tone" : "town",
              "tray":"train",
              "seedy":"city",
              "Leaving": "living",
              "bored":"born",
              "whirl":"world"
              }
    
    # use these given three lines to do the replacement
    rep = dict((re.escape(k), v) for k, v in journeydict.items()) 
    #Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest 
    versions
    pattern = re.compile("|".join(journeydict.keys()))
    text = pattern.sub(lambda m: journeydict[re.escape(m.group(0))], journey)
    
    print(journey)
    print(text)
    

    【讨论】:

    • 在不敏感的情况下如何使用它?我尝试添加标志 re.I,但尝试失败
    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2022-11-25
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多