簡體   English   中英

在python3.8中讀取文本文件並拆分為單獨的單詞,使用discord.py

[英]Reading a text file and splitting into separate words in python3.8, using discord.py

我正在嘗試使用 python 3.8 和 discord.py 制作 discord 機器人。 該機器人的 function 用於讀取文本文件並將每個單詞作為單獨的消息寫出,然后將其發送到 discord 服務器。 現在我有了文本文件,它可以打印出單詞,但不能單獨打印。

下面是相關代碼:

f = open("test.py")

@client.event
async def on_message(message):
    if message.content.startswith('r!help'):
        channel = message.channel
        await channel.send('Help')
    elif message.content.startswith('r!start'):
        channel = message.channel
        await channel.send('Starting Story...')
        await channel.send(f.readlines())

我讀了其他一些答案,他們說f.readlines()可以解決問題,但它只發送一行文本。 我試過了

def script_message():
with open('words.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)    

然后嘗試使用await channel.send(script_message())調用 function 但這給我留下了錯誤,它要求我更正語法。 那么如何將文本文件的內容作為單獨的消息發送呢?

async def script_message(channel):
    with open("words.txt") as f:
        data = f.readlines()
    for i in data:
        for j in i.split(" "):
            await channel.send(j)

在你的on_message事件中

elif message.content.startswith('r!start'):
    await message.channel.send('Starting Story...')
    await script_message(message.channel)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM