Python - 如何删除某个符号后所有行中的所有字符?

标签 python regex

我想删除所有行中 @ 符号之后的所有字符。 我写了一段代码:

#!/usr/bin/env python
import sys, re, urllib2
url = 'http://varenhor.st/wp-content/uploads/emails.txt'
document = urllib2.urlopen(url)
html = document.read()

html2 = html[0]
for x in html.rsplit('@'):
    print x

但它只删除 @ 符号并将其余字符复制到下一行。 那么我如何修改这段代码,删除 @ 之后所有行中的所有字符? 我应该使用正则表达式吗?

最佳答案

你 split 的次数太多了;使用str.rpartition()相反,忽略 @ 之后的部分。每行执行此操作:

for line in html.splitlines():
    cleaned = line.rpartition('@')[0]
    print cleaned

或者,对于较旧的 Python 版本,将 str.rsplit() 限制为仅 1 个分割,并再次仅获取第一个结果:

for line in html.splitlines():
    cleaned = line.rsplit('@', 1)[0]
    print cleaned

我用了str.splitlines()无论换行样式如何,都可以干净地分割文本。您还可以直接循环 urllib2 响应文件对象:

url = 'http://varenhor.st/wp-content/uploads/emails.txt'
document = urllib2.urlopen(url)
for line in document:
    cleaned = line.rpartition('@')[0]
    print cleaned

演示:

>>> import urllib2
>>> url = 'http://varenhor.st/wp-content/uploads/emails.txt'
>>> document = urllib2.urlopen(url)
>>> for line in document:
...     cleaned = line.rpartition('@')[0]
...     print cleaned
... 
ADAKorb...
AllisonSarahMoo...
Artemislinked...
BTBottg...
BennettLee...
Billa...
# etc.

关于Python - 如何删除某个符号后所有行中的所有字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23984964/

相关文章:

python - 如何有效地获取Python中两个列表中元素的平均值

javascript - 密码验证正则表达式之外的数字或特殊字符要求

java - 为什么字符串中的最后一个数字与正则表达式组不匹配?

javascript - 将字符串转换为表情符号

python - 以数字 5 开头的正则表达式

python - 如何找出对象是否具有属性?

python - 无法在 C 程序中链接 Python 库

python - 正则表达式以及如何获取捕获的值

python - 如何将不需要模型的应用程序添加到 django 管理站点?

python - 当我尝试在 Python 上使用 Ursina 时出现黑屏