![](/img/trans.png)
[英]I'm trying to export a Python list to a .txt file, but the text file ends up having too few lines
[英]I'm trying to make a bot send 10 lines of text from an actual txt file of 700 lines
我正在使用 Discord.py 编写一个不和谐的机器人,但我不知道如何使其工作。
@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 个单词。有人可以帮助我吗?
您可以使用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)
您可以像这样使用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)
其他答案是有效的,但如果您希望代码更简单且只有一行,您可以使用:
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
单词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.