python - 如何从字符串中删除\n 和\r

标签 python html python-3.x file-writing

我目前正在尝试从该网站获取代码:http://netherkingdom.netai.net/pycake.html 然后我有一个 python 脚本解析出 html div 标签中的所有代码,最后将 div 标签之间的文本写入文件。问题是它在文件中添加了一堆\r 和\n 。我怎样才能避免这种情况或删除\r 和\n。这是我的代码:

import urllib.request
from html.parser import HTMLParser
import re
page = urllib.request.urlopen('http://netherkingdom.netai.net/pycake.html')
t = page.read()
class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print(data)
        f = open('/Users/austinhitt/Desktop/Test.py', 'r')
        t = f.read()
        f = open('/Users/austinhitt/Desktop/Test.py', 'w')
        f.write(t + '\n' + data)
        f.close()
parser = MyHTMLParser()
t = t.decode()
parser.feed(t)

这是它生成的文件:

b'
import time as t\r\n
from os import path\r\n
import os\r\n
\r\n
\r\n
\r\n
\r\n
\r\n'

最好我还希望删除开头的 b' 和最后的 '。我在 Mac 上使用 Python 3.5.1。

最佳答案

一个简单的解决方案是去除尾随空格:

with open('gash.txt', 'r') as var:
    for line in var:
        line = line.rstrip()
        print(line)

rstrip() 相对于使用 [:-2] 切片的优势在于,这对于 UNIX 样式文件也是安全的。

但是,如果您只想摆脱 \r 而它们可能不在行尾,那么 str.replace() 就是您的选择 friend :

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

如果您有一个字节对象(即开头的 b'),您可以使用以下方法将其转换为 native Python 3 字符串:

line = line.decode()

关于python - 如何从字符串中删除\n 和\r,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35830924/

相关文章:

python - 修复数据框中重复的索引名称

javascript - 将 HTML 中具有全名的类列表转换为 JSON

python-3.x - 无法在 AWS Lambda 中导入 Pandas

python - 如何在 Python 3 中找到光标的坐标?

python - 错误 models.py Django

python - Ctypes:将返回的指针映射到结构

Python Pandas : Boolean indexing on multiple columns

html - 在我的 HTML 代码中,我没有找到改变页面显示的代码行,但该行代码显示在 Inspect Element 中

javascript - AngularJS + Ionic - 将内容 append 到另一个页面/ View

python - pysftp putfo 在 SFTP 服务器上创建一个空文件,但不传输来自 StringIO 的内容