简体   繁体   English

使用python使用pandas读取文本文件

[英]Reading text file using pandas using python

I am very new to Python.我对 Python 很陌生。 I am trying to read my text file using python Data Science library Pandas.我正在尝试使用 python 数据科学库 Pandas 读取我的文本文件。 But I get an error of Unicode which I don't understand.If you could help me then it would be very beneficial to me.但是我收到了一个我不明白的 Unicode 错误。如果你能帮助我,那对我来说非常有益。 I am uploading my code here:我在这里上传我的代码:

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

Error Code:错误代码:

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

Because the data inside a space character, CVS perceives this as a different column.由于空格字符内的数据,CVS 将其视为不同的列。 As a solution to this, separate the data with a different character.作为解决方案,将数据与不同的字符分开。 Then make the sep value this character.然后将 sep 值设为这个字符。 Example;例子;

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 = ";")

You can also look at this answer你也可以看看这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM