gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:35:20 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to replace multiple substrings of a string?

(26 个回答)


1年前关闭。




这是我的任务

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 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)

关于python - 有没有更短的方法来替换字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com