有一种更简便的方法可以替换字符串中的单词吗?

2024-06-08 14:01:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的任务

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的string replace方法来修复这个字符串,并将新版本打印到控制台。你知道吗

我就是这么做的

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)

Tags: ortheinreplaceanywherejustgoingtray
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)

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

相关问题 更多 >