Python在找到特定字符串时分割文本文件的内容

2024-09-28 19:18:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用下面的代码分割每2000个字符读取一次的文本文件的内容,以确保不超过discord.py消息限制

这可以很好地工作,但有一个小问题,就是有时消息中的一个单词会被拆分为两条消息,因为代码只会在消息达到2000个字符时拆分消息

我在想,更好的解决方案是查找文本文件中每个内容块之间通用的特定字符串,并在找到该字符串时进行拆分

我目前使用的代码如下

with open(info["textfile"], 'r') as file:
                    msg = file.read(2000).strip()
                    while len(msg) > 0:
                        await message.author.send(msg)
                        msg = file.read(2000).strip()

我想我需要使用.contains来搜索字符串,然后分割文本文件的内容作为消息发送,但我无法确定如何实现这一点

文本文件内容的示例如下:

__**Competition**__: Professional Boxing - 10 Rounds Lightweight Bout 
__**Competitors:**__: Katie Taylor v Delfine Persoon 
__**Match Date:**__: Saturday, 22nd  August 
__**Match Time:**__: ST: 21:00 
__**Channels**__: DAZN USA   
   Sky Sports Box Office HD 
-----
__**Competition**__: Professional Boxing - 12 Rounds Heavyweight Bout 
__**Competitors:**__: Dillian Whyte v Alexander Povetkin 
__**Match Date:**__: Saturday, 22nd  August 
__**Match Time:**__: ST: 22:00 
__**Channels**__: DAZN USA   
   Sky Sports Box Office HD 
----- 

我在想,最好搜索“----”并在此时拆分文本文件的内容,然后将每组匹配数据作为单独的消息发送

感谢所有能够为这一问题提供帮助或解决方案的人


Tags: 字符串代码消息内容readmatchmsg解决方案
1条回答
网友
1楼 · 发布于 2024-09-28 19:18:52

感谢dantechguy和Thomas Weller的帮助,我遇到的问题的解决方案如下:

with open(info["textfile"], 'r') as file: # using with to open file means we don't have to close it after finishing
                    msg = file.read().strip().split ("          ") # reads content of textfile and split when "         -" is found and creates list of strings.
                    for item in msg:  # for loop to call each item
                        print (item) # print to double check output 
                        await message.author.send(item) # send each item as a new message in discord.

正如他们在评论中所解释的,需要做的就是在“-”上拆分字符串,将字符串拆分为字符串列表,然后将每个项目作为消息发送

相关问题 更多 >