是否有更短的方法来替换字符串中的单词? [重复]

问题描述 投票:4回答:2

这是我的任务

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)
python str-replace
2个回答
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
投票

可能比您给定的方法更长;-)。

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)
© www.soinside.com 2019 - 2024. All rights reserved.