You can break a line into words using words = line.split()
, count the words, then rejoin the words into a single string using text = ' '.join(words)
.
Splitting lines into words to send the first n words
The following code will send the first n
words of the file:
n = 5
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
words = []
while len(words) < n:
line = next(jeff_file) # will raise exception StopIteration if fewer than n words in file
words.append(line.split())
await ctx.send(' '.join(words[:n]))
Splitting lines into words to send n random words
The following code will read all words from the file, then select n words at random and send those:
import random
n = 5
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
words = [w for line in jeff_file for w in line.split()]
n_random_words = random.sample(words, n) # raises exception ValueError if fewer than n words in file
# n_random_words = random.choices(words, k=n) # doesn't raise an exception, but can choose the same word more than once if you're unlucky
await ctx.send(' '.join(n_random_words))
Sending the first n lines
The following code will read and send the first n lines from the file:
n = 5
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
for _ in range(n):
line = next(jeff_file) # will raise exception StopIteration if fewer than n lines in file
await ctx.send(line)
Sending the first n lines, or fewer lines if there are fewer than n lines in file
n = 5
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
try:
for _ in range(n):
line = next(jeff_file)
await ctx.send(line)
except StopIteration:
pass
Sending n random lines
The following code will read the whole file and send n random lines:
import random
n = 5
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
all_lines = [line for line in jeff_file]
n_lines = random.sample(all_lines, n) # will raise exception ValueError if fewer than n words in file
# n_lines = random.choices(all_lines, k = n) # doesn't raise an exception, but might choose the same line more than once
await ctx.send(line)