Pandas读取来自Gutenberg项目的文本标记时出错

2024-04-24 01:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Gutenberg项目的一本书创建Python wordcloud。你知道吗

如果我选择Jule Verne的书A Journey to the Centre of the Earth并下载纯文本UTF-8文件,那么当我使用read\u 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\U csv文件,但我无法解析文本。你知道吗


Tags: 文件csvthe项目文本importpandasread
1条回答
网友
1楼 · 发布于 2024-04-24 01:14:49

熊猫是为结构化数据而设计的。这意味着一些组织成行和列的东西,比如电子表格或矩阵。它可以尝试一个文本文件,但松散的文本太杂乱无章,熊猫无法解析。你知道吗

你可能想做的是把它分成一个句子列表,然后把这个列表输入熊猫。你知道吗

下面是一个简单的例子:

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)

相关问题 更多 >