使用python使用熊猫读取文本文件

时间:2018-12-24 14:04:00

标签: python pandas

我对Python很陌生。我正在尝试使用python数据科学图书馆Pandas读取文本文件。但是我收到一个我不理解的Unicode错误,如果您能帮助我,那对我非常有益。我在这里上传代码:

import pandas as pd
text = pd.read_csv("/home/system/Documents/Heena/NLP/modi.txt", sep = " ", header = None)

错误代码:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/system/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 678, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/home/system/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 446, in _read
    data = parser.read(nrows)
  File "/home/system/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1036, in read
    ret = self._engine.read(nrows)
  File "/home/system/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1848, in read
    data = self._reader.read(nrows)
  File "pandas/_libs/parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read
  File "pandas/_libs/parsers.pyx", line 891, in pandas._libs.parsers.TextReader._read_low_memory
  File "pandas/_libs/parsers.pyx", line 945, in pandas._libs.parsers.TextReader._read_rows
  File "pandas/_libs/parsers.pyx", line 932, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas/_libs/parsers.pyx", line 2112, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 62 fields in line 7, saw 67

1 个答案:

答案 0 :(得分:0)

由于数据中包含空格字符,因此CVS会将其视为不同的列。作为解决方案,请使用其他字符分隔数据。然后将sep值设为此字符。例子;

test.csv

data1;data2;data3
My dear countrymen;12;test data1
I convey my best wishes to all of you on this auspicious occasion of Independence Day.;45;test data2

test.py

import pandas as pd
text = pd.read_csv("test.csv", sep = ";")

您也可以查看此answer