我正在尝试使用 pandas read_csv 读取 CSV 文件。数据看起来像这样(示例)
thing;weight;price;colour
apple;1;2;red
m & m's;0;10;several
cherry;0,5;2;dark red
由于 HTML 转义的符号,根据 pandas,第二行将包含 5 个字段。我如何确保该内容被正确读取?
这里的例子几乎就是我的数据的样子:分隔符是“;”,没有字符串引号,cp1251 编码。 我收到的数据非常大,读取它必须在一步中运行(意味着没有在 python 之外进行预处理)。
我没有在 pandas 文档中找到任何引用(我使用的是 pandas 0.19 和 python 3.5.1)。有什么建议么?提前致谢。
最佳答案
Unescape the html character references :
import html
with open('data.csv', 'r', encoding='cp1251') as f, open('data-fixed.csv', 'w') as g:
content = html.unescape(f.read())
g.write(content)
print(content)
# thing;weight;price;colour
# apple;1;2;red
# m & m's;0;10;several
# cherry;0,5;2;dark red
然后以通常的方式加载 csv:
import pandas as pd
df = pd.read_csv('data-fixed.csv', sep=';')
print(df)
产量
thing weight price colour
0 apple 1 2 red
1 m & m's 0 10 several
2 cherry 0,5 2 dark red
虽然数据文件“相当大”,但您似乎有足够的内存将其读入 DataFrame。因此,您还应该有足够的内存来将文件读入单个字符串:f.read()
。通过一次调用 html.unescape
转换 HTML 比在许多较小的字符串上调用 html.unescape
的性能更高。这就是为什么我建议使用
with open('data.csv', 'r', encoding='cp1251') as f, open('data-fixed.csv', 'w') as g:
content = html.unescape(f.read())
g.write(content)
而不是类似的东西
with open('data.csv', 'r', encoding='cp1251') as f, open('data-fixed.csv', 'w') as g:
for line in f:
g.write(html.unescape(line))
如果你需要多次读取这个数据文件,那么修复它(并保存它)是值得的
到磁盘)所以你不需要每次你想解析时调用 html.unescape
数据。这就是为什么我建议将未转义的内容写入 data-fixed.csv
。
如果读取此数据是一次性任务,并且您希望避免写入磁盘的性能或资源成本,那么您可以使用 StringIO(内存中的文件类对象):
from io import StringIO
import html
import pandas as pd
with open('data.csv', 'r', encoding='cp1251') as f:
content = html.unescape(f.read())
df = pd.read_csv(StringIO(content), sep=';')
print(df)
关于python - 当其中有 HTML 转义字符串时,使用 python (pandas) 读取 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40399640/