在换行处使用regex/python删除“=/r/”匹配文本

2024-06-17 13:08:01 发布

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

我有以下代码可以将一段文本与电子邮件隔离开来:

for part in mail.walk():
    if part.get_content_type() == 'text/plain':
        content = part.get_payload()
        message = re.compile(r'\%(.+?)\%', re.DOTALL).findall(content)
        print message

但是,当它prints时,我得到如下结果:

^{pr2}$

如何删除每行末尾的=\r\?谢谢您!在


Tags: 代码textin文本remessageforget
3条回答

如果print消息中给出了以下信息:

['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et erat libe=\r\nro. Ut lacinia ante euismod nibh feugiat pellentesque. Suspendisse vestibul=\r\n

…那么您就没有任何要删除的\字符或r字符。有回车符,Python将其显示为\r(回车符)字符。还有新行,Python显示为\n。在

这是因为您看到的是字符串的repr,而不是str。通常,print x打印str……但是list(或其他集合)的str包含{},而不是{},或其每个元素。在

如果您实际打印str,如print message[0],您将看到如下内容:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et erat libe= ro. Ut lacinia ante euismod nibh feugiat pellentesque. Suspendisse vestibul=

所以,您不想删除'\r\,或者删除{},或者用换行符替换{},或者类似的任何东西。字符串已经正确。(如果需要,可以将Windows样式\r\n换行符转换为Unix样式\n,但不必这样做。)

当然,除了每行末尾的=字符。要解决这个问题:

s.replace('=\r', '\r')

或者,要为列表中的每个字符串修复它:

^{pr2}$

此代码应删除文本中的任何“=\r\”。在

result = re.sub("=\\\\r\\\\", "", searchText)

我们能看看开头的文字吗?在

从我现在所看到的,你可以修改你的代码来做以下事情

for part in mail.walk():
    if part.get_content_type() == 'text/plain':
        content = part.get_payload()
        message = re.compile(r'\%(.+?)\%', re.DOTALL).findall(content)
        # This will just substitue the '=\r\' with nothing.
        message = re.sub(r'=\\r\\', '', message)
        print message

相关问题 更多 >