2

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 ?

3
  • What do you mean, "sequence string"? Commented Feb 28, 2014 at 17:06
  • I think you can replace ' '+word+' ' by str(count) or use regex word boundary. Commented Feb 28, 2014 at 17:08
  • These elements are str(numbers). I want to rename those elements as numbers in sequence. If you noticed in the example I want to save these elements as sequential numbers and I index the assignment to a dict Commented Feb 28, 2014 at 17:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.