Hit*_*anA 13 html python file-writing python-3.x
我目前正在尝试从这个网站获取代码: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)
Run Code Online (Sandbox Code Playgroud)
这是它产生的结果文件:
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'
Run Code Online (Sandbox Code Playgroud)
我最好还是先删除b'和last'.我在Mac上使用Python 3.5.1.
cda*_*rke 24
一个简单的解决方案是去除尾随空格:
with open('gash.txt', 'r') as var:
for line in var:
line = line.rstrip()
print(line)
Run Code Online (Sandbox Code Playgroud)
rstrip()过度使用[:-2]切片的优点是,这对于UNIX样式文件也是安全的.
但是,如果你只想摆脱\r它们并且它们可能不在最后,那么str.replace()你的朋友是:
line = line.replace('\r', '')
Run Code Online (Sandbox Code Playgroud)
如果您有一个字节对象(这是领先的b'),您可以使用以下命令将其转换为本机Python 3字符串:
line = line.decode()
Run Code Online (Sandbox Code Playgroud)