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

Recommended Answers

All 4 Replies

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])

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

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

Thank you it works!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.