Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to replace words in a string? [duplicate]

This is my task

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

Gross. Okay, so for this exercise, your job is to use Python's string replace method to fix this string up and print the new version out to the console.

This is what I did

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)
like image 467
David Avatar asked Mar 04 '23 00:03

David


2 Answers

Here is a sample way to replace words from text. you can use python re package.

please find the below code for your guidance.

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)
like image 162
user12595616 Avatar answered Mar 05 '23 12:03

user12595616


Probably a longer way than you given ;-).

As given at 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)
like image 33
Rahul Talole Avatar answered Mar 05 '23 14:03

Rahul Talole