美丽汤 正则表达式

7
我刚刚在Python中运行了以下代码,以将特定电子邮件从IMAP文件夹中取出。提取部分正常工作,BeautifulSoup部分也可以,但输出中有很多'\r'和'\n'。我尝试使用REGEX sub函数删除它们,但它不起作用...甚至没有给出错误消息。有什么想法吗?我附上了代码...请注意(这不是完整的代码,但我发布的代码以上的所有内容都正常工作。它仍然打印输出,它是“漂亮的”,但\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内容的例子吗? - Eypros
你能给一个输入的例子吗?另外,你的示例中的for循环缩进不正确。 - Eolmar
1
使用.replace()进行字符串替换。https://www.tutorialspoint.com/python/string_replace.htm - innicoder
更改了帖子以反映您上面的问题。 - Obie
谢谢Elvir!那个方法可行。不知道为什么正则表达式没起作用。 - Obie
2个回答

4

您可以使用这个一行正则表达式语句:

soup = re.sub('\\r*n*', '', soup)

或者您可以使用以下方法:
soup = re.sub('\\r', '', soup)
soup = re.sub('\\n', '', soup)

https://regexr.com/3nnp1


2
< p >那直接使用< code >replace命令呢?由于它不是正则表达式,所以应该更快。< /p >
soup.replace("\n","").replace("\r","")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接