Python 3.x 无法删除python3字符串中的\n和\t?
因此,我一直在尝试格式化从CL获取的网页,以便将其发送到我的电子邮件, 但这就是我每次尝试删除Python 3.x 无法删除python3字符串中的\n和\t?,python-3.x,Python 3.x,因此,我一直在尝试格式化从CL获取的网页,以便将其发送到我的电子邮件, 但这就是我每次尝试删除\n和\t b'\n\n\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n\n\t\n\n\n\t \n\t\t\t \n\t \n\t\t \n\t\t\t \n 0 favorites\n \n\n\t\t \n\t\t ∨ \n\t\t ∧ \n\t\t \n \n \n \n\t \tCL wenatchee all personals casual encounters\n \n \
\n
和\t
b'\n\n\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n\n\t\n\n\n\t
\n\t\t\t
\n\t
\n\t\t
\n\t\t\t
\n 0 favorites\n
\n\n\t\t
\n\t\t
∨
\n\t\t
∧
\n\t\t
\n \n
\n
\n\t \tCL wenatchee all personals casual encounters\n
\n
\n\t\t
\n\t
\n
\n\n\t\t
\n\t\t\t
\n\t\n\t\t\n\t\n\n\n\nReply to: 59nv6-4031116628@pers.craigslist.org\n
\n\n\n\t
\n\t\n\t\tflag [?] :\n\t\t\n\t\t\tmiscategorized\n\t\t\n\t\t\tprohibited\n\t\t\n\t\t\tspam\n\t\t\n\t\t\tbest of\n\t\n
\n\n\t\t
Posted: 2013-08-28, 8:23AM PDT
\n
\n\n
\n \n Well... - w4m - 22 (Wenatchee)\n
我试过脱衣舞、替换舞,甚至是正则舞,但没什么不对劲的,它总是出现在我的电子邮件中,不受任何事情的影响
代码如下:
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.split
和string.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)
你的问题是,尽管有所有相反的证据,你仍然有一个
bytes
对象,而不是你所希望的str
。因此,您的尝试没有结果,因为如果没有指定编码,就无法将任何内容(正则表达式、替换参数等)匹配到html
字符串
您需要做的是首先输入字节
就我个人而言,我最喜欢的清理空白的方法是使用string.split
和string.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)
此代码不运行,并且您的帖子实际上未格式化。格式化您的问题,并发布一个我们可以复制和粘贴以重现您的问题的帖子,否则您不可能获得任何帮助。此代码无法运行,您的帖子几乎未格式化。格式化您的问题,并发布一个我们可以复制和粘贴以重现您的问题的帖子,否则您不太可能得到任何帮助。是的,这很有效!我不知道它仍然是编码的,这就是让我绊倒的原因@亨利:非常感谢你。这个答案太棒了。是的,这个成功了!我不知道它仍然是编码的,这就是让我绊倒的原因@亨利:非常感谢。这个答案太棒了