0

Hi

Am trying to get my head around using with in some code which is putting 2 files together using random.choice. How do I prevent repeats with random.choice?

with open(name, "r") as f1:
  beginnings = [word.rstrip(" \n") for word in f1]

with open("conjunct.txt", "r") as f2:
  endings = [word.rstrip(" \n") for word in f2]

with open(name, "w") as f3:
  for beginning in beginnings:
      f3.write('%s %s' % (beginning, random.choice(endings)))
      f3.write(os.linesep)

Thanks for any assist,
jkrueger

2
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by jkrueger
0

Use random.shuffle instead.

random.shuffle(endings)

for ctr, beginning in enumerate(beginnings):
    ## assumes there are at least as many endings as beginnings
    f3.write('%s %s\n' % (beginning, endings[ctr])

Edited by woooee: n/a

0

Thank you, I'm having a difficult time using with.
Everything after your code got an error, I have to do more with random etc., something I'm not getting.

with open(name, "w") as f3:
  random.shuffle(endings)

  for ctr, beginning in enumerate(beginnings):
    ## assumes there are at least as many endings as beginnings
    f3.write('%s %s\n' % (beginning, endings[ctr])
    f3.write(os.linesep)

Here is the error message.

f3.write(os.linesep)
     ^
SyntaxError: invalid syntax

Edited by jkrueger: need code example

0

Add one more closing parens to this line
f3.write('%s %s\n' % (beginning, endings[ctr]))

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.