无法删除python3字符串中的n和t



所以我一直在尝试格式化CL拍摄的网页,以便将其发送到我的电子邮件中,但这是我每次尝试删除nt 时都会想到的

b'nnntntntntntntnnnntnnnt
nttt
nt
ntt
nttt
n 0 favoritesn
nntt
ntt
∨
ntt
∧
ntt
n n
n
nt tCL wenatchee all personals casual encountersn
n
ntt
nt
n
nntt
nttt
ntnttntnnnnReply to: 59nv6-4031116628@pers.craigslist.orgn
nnnt
ntnttflag [?] :nttntttmiscategorizednttntttprohibitednttntttspamnttntttbest ofntn
nntt
Posted: 2013-08-28, 8:23AM PDT
n
nn
n n Well... - w4m - 22 (Wenatchee)n

我尝试过剥离、替换甚至regex,但没有什么能让它困扰,它总是出现在我的电子邮件中,不受任何影响。

这是代码:

try:
    if url.find('http://') == -1:
        url = 'http://wenatchee.craigslist.org' + url
    html = urlopen(url).read()
    html = str(html)
    html = re.sub('s+',' ', html)
    print(html)
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    s = smtplib.SMTP('localhost')
    s.sendmail(me, you, msg.as_string())
    s.quit()

您的问题是,尽管有所有相反的证据,您仍然有一个bytes对象,而不是您希望的str。因此,您的尝试没有结果,因为如果没有指定编码,就无法将任何内容(正则表达式、替换参数等)与html字符串相匹配。

您需要做的是首先解码字节。

就我个人而言,我最喜欢的清理空白的方法是使用string.splitstring.join。下面是一个工作示例。我删除了所有的空格,并用单个空格替换它们。

try:
    html = urlopen('http://wenatchee.craigslist.org').read()
    html = html.decode("utf-8") # Decode the bytes into a useful string
    # Now split the string over all whitespace, then join it together again.
    html = ' '.join(html.split())
    print(html)
    s.quit()
except Exception as e:
    print(e)

最新更新