我目前正在尝试从该网站获取代码: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/