1

I'm a bit new to python so sorry if this is a basic question.

I have a file that looks something similar to this:

Zr  1   1   1
Zr  1   1   1
Zr  1   1   1
Zr  1   1   1

repeated over quite a few lines. I need to replace strings in the first column randomly with another specified string (edited for clarity), whilst keeping columns 2, 3, and 4 the same.

Any ideas how to do this? I get that I should feed the first column into an array, index each one and then randomly swap out, but I'm not sure how to proceed.

Thanks.

Kathryn :)

EDIT: FIXED.

Thanks for all of your help guys, just needed random.sample :)

  • I'm not sure what the question is. Can you not just split the first line at the spaces, count the length of the array, then use randint(0,9) (or whatever range you want) to create an array of equivalent length and write that back into your file? – Moritz Aug 20 '12 at 10:05
  • Sorry, I'm just trying to clarify. What part is confusing? – Kathryn Bradley Aug 20 '12 at 10:09
  • Well, what you are describing: "I get that I should feed the first column into an array, index each one and then randomly swap out" sounds correct. So are you asking for help on how specifically to implement this (i.e. sample code) or do you want to know how to insert the column back into the file? I guess I'm just confused as to where exactly the problem is, as the approach you are describing sounds like it would work. – Moritz Aug 20 '12 at 10:23
  • Yeah, I understand how I should implement it because I've programmed in C before, but I have no idea how to write it in python (so I'm looking for references/sample code). Thanks :) – Kathryn Bradley Aug 20 '12 at 10:30

2 Answers2

2

Use this to generate a random string

import os
random_string = os.urandom(string_length)

To loop over a file line by line, do

with open('file') as fd:
    for line in fd:
        # do stuff

No need to close the file handle

use split to well, split on whitespace and place the result in an array (indexing starts at 0) Read more at docs.python.org

Please update your question with some code when you have gotten that far... Good luck

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • Okay, thanks, I'll have a go. I don't need to generate a random string, I need to replace strings in the first column with another specified string, for example replacing Zr with O twice out of 100 occurences (I'm dealing with atoms here!) – Kathryn Bradley Aug 20 '12 at 10:13
2

I would strongly suggest reading a python primer, the way your problem solved can be done in two steps

  1. read items from file - reference

  2. use math.random() to change random string- reference

by know how to do these points you can easily achieve what you intend to do.

Community
  • 1
  • 1
Vaibhav Mishra
  • 11,384
  • 12
  • 45
  • 58