gpt4 book ai didi

python - Pandas read_csv 错误标记古腾堡项目中的文本

转载 作者:行者123 更新时间:2023-12-01 08:19:33 25 4
gpt4 key购买 nike

我正在尝试使用古腾堡计划中的一本书创建一个 Python 词云。

如果我选择儒勒·凡尔纳的书A Journey to the Centre of the Earth并下载纯文本 UTF-8 文件,当我使用 read_csv 时,我从 pandas 收到错误。

这是我正在使用的代码:

from wordcloud import WordCloud, STOPWORDS 
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('pg18857.txt',delimiter=' ')

我收到以下错误消息:

pandas.errors.ParserError: Error tokenizing data. C error: Expected 14 fields in line 176, saw 15

我在 pd.read_csv 中尝试了多个选项,但无法解析文本。

最佳答案

Pandas 专为结构化数据而设计。这意味着组织成行和列的东西,例如电子表格或矩阵。它会尝试一个文本文件,但是松散的文本对于 Pandas 来说太困惑了,无法解析。

您可能想要做的是将其拆分为句子列表,然后将该列表输入 Pandas。

这是一个简单的例子:

with open('pg18857.txt') as f:
content = f.readlines()
# Remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
df = pd.DataFrame(content)

关于python - Pandas read_csv 错误标记古腾堡项目中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com