我有一个代码,它读取文件并从该文件中随机选择一行,并通过DM作为不和谐机器人发送。但是,我希望它读取txt文件的某个部分,该部分以哪个字符开头和结尾。 例如: 你好 ,
这是我正在使用的代码,它读取随机行并通过DM发送它:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
emails = []
for email in emailFile:
emails.append(email)
@bot.command(pass_context = True)
@commands.cooldown(1, 30, commands.BucketType.user)
@commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
msg = emails
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30 Seconds Before Using This Command Again. If you do not wait the full time then you won't be sent an alt.")
这是我的修订版:
emailFile = open("C:/Users/jacob/Downloads/Uplay_Formatted.txt", "r",
encoding="utf16").read()
parse = False
email = []
for com in emailFile.split('\n'):
if com.startswith(',Credentials'):
parse = True
elif com.startswith(',Credentials'):
parse = False
if parse:
email.append(com)
@bot.command(pass_context = True)
@commands.cooldown(1, 30, commands.BucketType.user)
@commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
msg = email
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen
To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30
Seconds Before Using This Command Again. If you do not wait the full
time then you won't be sent an alt.")
答案 0 :(得分:1)
您还可以使用startswith()和endswith()示例here
例如,在你的情况下;这将是这样的:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
read_emails = emailFile.read()
emails = [com for com in read_emails.split() if com.startswith(',') and com.endswith(',')]
根据您的要求在开始和结束之间显示内容。试试这个:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r", encoding="utf8").read()
parse = False
for com in emailFile.split('\n'):
if com.startswith(',Credentials'):
parse = True
elif com.startswith(',Credentials'):
parse = False
if parse:
#do stuff
如果您只是想从文本文件中获取电子邮件地址。
import re
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r", encoding="utf8").read()
email = []
for com in emailFile.split():
if re.match(r'[\w\.-]+@[\w\.-]+', com):
email.append(com)
答案 1 :(得分:0)
尝试使用正则表达式https://docs.python.org/2/library/re.html
您可以匹配以单词'嗨'开头的行。 re.match('^Hi', line)
^表示该行的开头,还有一些其他可能有用的特殊字符。