有没有更短的方法来替换字符串中的单词?

时间:2019-12-25 14:08:53

标签: python str-replace

这是我的任务

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)

2 个答案:

答案 0 :(得分:4)

这里是从文本替换单词的示例方法。您可以使用 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)

答案 1 :(得分:2)

可能比您指定的;-)更长。

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)