【发布时间】:2018-09-21 01:04:52
【问题描述】:
我刚刚在 Python 中运行了以下代码,以将所有特定电子邮件从 IMAP 文件夹中取出。提取部分工作正常,BeautifulSoup 部分工作正常,但输出中有很多“\r”和“\n”。
我尝试使用 REGEX 子函数删除这些,但它不起作用……甚至没有给出错误消息。知道有什么问题吗?我附上代码...请注意(这不是完整的代码,但我发布的代码上方的所有内容都可以正常工作。它仍然打印输出,它是“美化的”,但 \r 和 \n 仍然存在。已尝试使用 find_all() 但这也不起作用。
mail.list() # Lists all labels in GMail
mail.select('INBOX/Personal') # Connected to inbox.
resp, items = mail.search(None, '(SEEN)')
items = items[0].split() # getting the mails id
for emailid in items:
# getting the mail content
resp, data = mail.fetch(emailid, '(UID BODY[TEXT])')
text = str(data[0]) # [1] don't forget to add this back
soup = bs(text, 'html.parser')
soup = soup.prettify()
soup = re.sub('\\r\\n', '', soup)
print(soup)
【问题讨论】:
-
你能提供一个
items内容的例子吗? -
你能举个输入例子吗?此外,您的示例中的 for 循环也没有正确缩进
-
只用
.replace()tutorialspoint.com/python/string_replace.htm -
已更改帖子以反映您的上述问题。
-
感谢埃尔维尔!那行得通。想知道为什么 REGEX 不起作用。
标签: python regex beautifulsoup