简体   繁体   中英

python : replace words in string

I am new to python so I have this question. First let me tell you what I want to do. I have a file that contains something like this:

-0
    1
    3
    5
-00
    2
    3
    18
    321
...

I want to take each element except -0, -xxxx string and convert them into sequence numbers, for example:

-0
    1
    2
    3
-00
    4
    2
    5
    6
...

I have done this and I have saved the index to a dictionary But I want to replace them inside the string too.

I want to replace the exact words, I do not want to replace words that may be contained to another word for example:

111 replaced by 6
not 445111 replaced by 6 ~>4456

I had this idea but I do not know if it is efficient or worth. For every elements inside -xxxx I will create a list, append its elements, then rename them and replace them, and then save them to the file. Any ideas ?

I think this is what you need:

for i, word in enumerate(z):
    if "-" not in word:
        if word in d.keys():
            z[i] = str(d[word])
        else:
            count = count + 1
            d[word] = count
            z[i] = str(count)

That way you can replace the words in-place and without any string manipulation.

I am not quite sure what you want to do. However, if the list elements and the string elements are supposed to be the same, why not just do str(elem) from the list. That way instead of replacing the elements within the string you are actually creating the string that you want to be there to begin with. It seems that you are only replacing "word" if it is not already in the dictionary. If it is already in the dictionary, you leave the word itself in the string.

Based on the code that you show, this would seem to do it

You can create a string list with

newz = []
for word in z:
   if "-" not in word:
     if word not in d.keys():
        count = count + 1
        d[word] = count
        newz.append(str(count))
     else:
        newz.append(word)
   else:
     newz.append(word)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM