我正在用Discord.py编写一个discord机器人,但我不知道如何使它工作。
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
for line in jeff_file:
await ctx.send(line)
该文件包含700个单词,但我希望它发送5个或10个单词。有人可以帮助我吗?
答案 0 :(得分:1)
您可以使用words = line.split()
将行划分为单词,对单词进行计数,然后使用text = ' '.join(words)
将单词重新组合为单个字符串。
以下代码将发送文件的前n
个字:
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]))
以下代码将从文件中读取所有单词,然后随机选择n个单词并将其发送:
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))
以下代码将从文件中读取并发送前n行:
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)
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
以下代码将读取整个文件并发送n条随机行:
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)
答案 1 :(得分:0)
您也许可以使用enumerate
并像这样打破循环:
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
with open('Available.txt', 'r') as jeff_file:
jeff_lines = jeff_file.readlines()
for i, line in enumerate(jeff_lines):
if i == 5:
break
else:
await ctx.send(line)
答案 2 :(得分:0)
其他答案是可行的,但是如果您希望代码更简单,一行代码,则可以使用:
n = 5
@client.command(alisases = ['readfile'])
@commands.check(is_it_me)
async def jeff(ctx):
await ctx.send(' '.join(open('Available.txt', 'r').read().split(' ')[:n]))
这将发送文档中的前n
个单词。