So i'm trying to create a translator in python(in a s60 device). So what 'm trying to do is to replace just one whole word without touching the other words. Here's an example

Original: "The brown fox jumps over the dog named brownie." I want to replace the word "brown" into "deathlesi"(Just ignore why) The result should be: "The deathlesi fox jumps over the dog named brownie." But instead it also changes "brownie" in the string which results to: "The deathlesi fox jumps over the dog named deathlesiie."

Since I'm trying to replace each and every word, sometimes it goes into a never ending paradox. Example: "I am stupid" I'm trying to change "I" into "ium" and this is what happens. "iumumumumumumumumumumumumumumumumumumumum.... am stupiuiuiuiuiuiuiuiuiuiuiuiuiuiuiuiuiuiuim..", it basically changes every "I" in the string and won't stop until there's no "I" in the string.

Any help? Thanks!

Edit: I already tried "stringhere".replace() but certain parts like a lowercase "i" usually replaces the "i" in stupid.

Here's another example: "People are getting excited at the giant hare." replacing "are" to "iume", instead of "People iume getting excited at the giant hare." it also replaced "hare" which resulted into "People iume getting excited at the giant hiume."

Supposedly I array'ed the sentence and translate each of them. That is my current method now. Basically converting each word into a array and converting each one of them. Then doing a

translated_sentence=["particulus:people", "iume:are", "geus:getting", "exchantus:excited", "d:at", "qun:the", "gesas:giant", "hsont:hare"]
sentence= "People are getting excited at the giant hare."
for i in translated_sentence do
element=i.split(":")
sentence=sentence.replace(element[1], element[0])

and still it throws a "particulus uime geus exchantus d qun gesas huime(instead of hsont)"

I just got it figured it out. I just splitted the string into an array, and preserved the formatting by cleaning the current word and doing a string.replace() to the original word.

sentence="The quick brown fox jumps over the lazy dog.".split(" ")
result=""

for i in sentence:

cleaned=clean(i) #removes the punctuations and stuff leaving the raw word.

translated=translate(cleaned) #returns the translated word

result=result+i.replace(cleaned,translated)+" "

return result
有帮助吗?

解决方案

Since you only want to find the first occurrence, you just need a way to keep track of it. You can do this many ways. As simple as this:

def replacer(original, looking_for, replace_with):
   ''' A straightforward way... '''
   return original.replace(looking_for, replace_with, 1)
   #return regex.sub(replace_with, looking_for, 1)

The number indicates how many occurrences do you want to replace. If there exists two, and you put 2, both occurrences will be replaced.

String is immutable, so you must re-assign the new string. Each time you do replace you are generating a new string.

You can also write a loop to find the N-th occurrence if you don't want the built-in.

I recommend making your post shorter (I mean fewer words, and more syntax highlight). Format it. Correct me if I didn't read your post correctly.

其他提示

This sounds like a regex scenario:

import re
x = "The brown fox jumps over the dog named brownie."
newstring = re.sub(r"(\s+|[:punct:]+|^)brown(\s+|[:punct:]+|$)",r"\1deathlies\2",x, flags=re.IGNORECASE)

Which yields:

>>> print newstring
The deathlies fox jumps over the dog named brownie.

Or:

x = "People are getting excited at the giant hare."
newstring = re.sub(r"(\s+|[:punct:]+|^)are(\s+|[:punct:]+|$)",r"\1iume\2",x, flags=re.IGNORECASE)

Which Yields:

>>> print newstring
People iume getting excited at the giant hare.

The first capture group (\s+|[:punct:]+|^) matches a space, punctuation or the beginning of the string, and the other group (\s+|[:punct:]+|$) matches the end of the string.

When making the replacement, the \1 and \2 put the puncuation or spacing back with the replaced text- making things neat.

PS

If you're lazy, just make the capture groups (\W+|^) and (\W+|$) ...

Just call replace function of string

"I am stupid".replace("I", "ium")

I don't have python with me right now, but how about making a function to convert the string into a list. You can take out white space, so the list would be [The, brown, fox, jumps...]. Then do a .replace.

You want to replace the exact equal word. not a string.replace()

replace "are" but don't replace "hare"

if that's the case

edited

as @Niall said Regular Expression search and replace is the best tool to satisfy your tasks.

alternatively, if you've just started learning Python and regex is too complicate. just split string to words using str.split() then loops through the words.

def simply_replace(string, search, replace):
    words = string.split(' ')
    for i in range(len(words)):
        if(words[i].lower() == search):
            words[i] = replace
    return ' '.join(words)

>>> simply_replace("I am stupid", 'i', 'ium')
'ium am stupid'
>>> simply_replace("The brown fox jumps over the dog named brownie.", 'brown', 'deathly')
'The deathly fox jumps over the dog named brownie.'
>>> simply_replace("People are getting excited at the giant hare.", 'are', 'ium')
'People ium getting excited at the giant hare.'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top