【问题标题】:file does not exist using DATA_DIR and DATA_FILE? Why?使用 DATA_DIR 和 DATA_FILE 的文件不存在?为什么?
【发布时间】:2020-04-10 12:26:06
【问题描述】:

当我从学校运行文件时,代码给了我这个错误:

error> reading data fileError tokenizing data. C error: Expected 2 fields in line 42, saw 3

文件和文件夹都存在于我的桌面中,但由于某种原因我无法查看文件... 我正在使用DATA_DIRDATA_FILE 变量。

您能否帮助代码找到并读取文件夹/文件内容?

代码:

import requests
import nltk
import textblob
import os
import glob
import csv
import pandas as pd
import sys

DEBUGGING = True
TOP_MOST = 10
#
#   Stopwords file:
stopwords = open("english-stop-words-large.txt")
stopwords = stopwords.read()
#print(stopwords)

DATA_DIR = 'DM.CW2'
DATA_FILES = 'benjamin-bunny.txt'

# txtFile = open("kim.txt")
# txtFile = txtFile.read()
try:
    df = pd.read_csv((DATA_FILES), na_filter=False)
except Exception as x:
    print ('error> reading data file' + str(x))
    sys.exit()

for (j, myfile) in zip(range(len(DATA_DIR)), DATA_FILES):
    with open( myfile) as f:
        raw_verse = f.read()
    f.close()
    if (DEBUGGING):
        print('raw_verse=', raw_verse)
    print('file=', myfile)


freq_words = [dict() for j in range(len(DATA_FILES))]

verse = textblob.TextBlob(raw_input().decode('utf-8'))
if DEBUGGING:
    print('verse=', verse)

    words = {}
    for w in verse.word_counts:
        if w not in stopwords:
            words[w] = verse.word_counts[w]
    if DEBUGGING:
        print(words)

sorted_words = sorted(words, key=words.__getitem__, reverse=True)
for (i, w) in zip(range(TOP_MOST), sorted_words):
    freq_words[j][w] = verse.word_counts[w]
    print(i, w, verse.word_counts[w])

#   For polarity and subjectivity:
testimonial = textblob.TextBlob(words)
print(testimonial.sentiment)

包含 .txt 文件的文件夹称为 DM.CW2。它在我的桌面上。文件 .txt 文件也在此文件夹中。

我正在使用 python 2.7。我相信我为此导入了所有必需的包。

【问题讨论】:

  • 注意:len(DATA_DIR)6,即字符串的长度。
  • 如果您添加您遇到的确切错误将会很有帮助。除非 DATA_FILES 与脚本位于同一目录中,否则它将无法找到它。尝试放置绝对路径,例如'/home/user/project/DM.CW2/benjamin-bunny.txt'
  • 我试过了,还是没有找到目录。而错误正是:error> reading data fileError tokenizing data。 C 错误:预计第 42 行中有 2 个字段,看到 3。

标签: python csv directory data-science filenotfoundexception


【解决方案1】:

如果没有您的数据文件,很难准确地说出发生了什么。也许将其添加到问题中。

您收到“错误标记数据。C 错误:预期第 3 行中的 2 个字段,看到 12”的错误意味着程序能够找到该文件,但在读取它时遇到问题。

有一些可能的问题,但如果不查看文件中的数据就无法判断。检查以下内容:

  1. 扩展名是.txt 而不是.csv 所以pandas.read_csv 可能不是读取文件的正确方法——这确实是文件格式的问题。

  2. 默认文件分隔符是逗号,但您的文件可能有不同的分隔符,例如制表符的空格。您可以尝试使用不同的分隔符

data = pd.read_csv('file1.csv', sep='\t')
or
data = pd.read_csv('file1.csv', sep=' ')
  1. 如果是 CSV 文件,它可能包含损坏的行,因此您可以使用以下命令跳过它们

data = pd.read_csv('file1.csv', error_bad_lines=False)

【讨论】:

  • 我尝试了这个修复,但没有奏效。我知道 pandas 可以使用 read_csv 函数读取任何文件。我设法找到了另一种方法来实现我的代码。谢谢你的时间。我会接受这个答案是正确的,因为我认为这是问题所在。
猜你喜欢
  • 1970-01-01
  • 2012-06-20
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多