【发布时间】:2018-01-28 04:56:17
【问题描述】:
我正在运行一个获取 UTF-8 编码网页的 Python 程序,我使用 pandas(read_html) 从 HTML 表中提取一些文本并将结果写入 csv 文件
但是,当我将此文本写入文件时,其中的所有空格都以意外编码写入(例如 \xd0\xb9\xd1\x82\xd0\xb8)。 为了解决这个问题,我添加了一行 i = i.split(" ") 之后,csv文件中的所有空格都替换为字符,示例如下:
['0', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '1', '', '', '', '', '', '', '', '', '', '', '', '', '', '2', '', '', '3\n0', '', '', '', '', '', '', '', 'number', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'last name', '', 'number', 'plan', 'NaN\n1', '', '', '', '', '', '', '', '', '', 'NaN', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'NaN', '', '', 'not', 'NaN\n2', '', '', '', '', '53494580', '', '', '', '', '', '', '', '', '', '+', '(53)494580', '', '', '', '', '', '', '', '', 'NP_551', 'NaN\n3', '', '', '', '', '53494581', '', '', '', '', '', '', '', '', '', '+', '(53)494581', '', '', '', '', '', '', '', '', 'NP_551', 'NaN\n4', '', '', '', '']
我想去掉字符 ('', ) 有没有办法解决这个问题? 任何指针将不胜感激。
代码python:
import pandas as pd
import html5lib
filename="1.csv"
file=open(filename,"w",encoding='UTF-8', newline='\n');
output=csv.writer(file, dialect='excel',delimiter =' ')
r = requests.get('http://10.45.87.12/og?sh=1&CallerName=&Sys=.79.83.86.51&')
pd.set_option('max_rows',10000)
df = pd.read_html(r.content)
for i in df:
i = str(i)
i = i.strip()
i = i.encode('UTF-8').decode('UTF-8')
i = i.split(" ")
output.writerow(i)
file.close()
【问题讨论】:
-
您只需要
split()即可摆脱所有空白 -
您可以尝试将
i.encode('UTF-8').decode('UTF-8')更改为i.decode('UTF-8')还是直接删除该行并发布您的结果? -
你能粘贴
requests.get('http://10.45.87.12/og?sh=1&CallerName=&Sys=.79.83.86.51&')的结果吗?我认为pd.read_html仅适用于 html 表格。对于大多数 HTML 解析任务,我会推荐 BeautifulSoup @johnred