【问题标题】:ValueError: 'text' is not in listValueError:“文本”不在列表中
【发布时间】:2017-09-17 10:41:21
【问题描述】:

当我尝试读取包含文本和日期字段的 csv 文件时 我收到一个错误

text_column_index = header.index('text')

ValueError: 'text' 不在列表中

代码:

with open(source_file_path, 'r') as input_file:
    csv_reader = csv.reader(input_file, delimiter='\t')
    header = next(csv_reader)
    text_column_index = header.index('text')
    date_column_index = header.index('date')
    word_frequency = {}
    for line in csv_reader:
        self.size += 1
        words = self.tokenize(line[text_column_index])
        date = line[date_column_index]
        if date > self.end_date:
            self.end_date = date
        elif date < self.start_date:
            self.start_date = date

我做错了什么?

【问题讨论】:

  • 添加print(header) 看看它包含什么?
  • 什么也没发生 嗯
  • 真的什么都没有发生?似乎至少应该打印空列表
  • 这就是我所做的 word_frequency = {} print(header)
  • 需要在报错之前加上print,否则报错就达不到了。

标签: python list indexing valueerror


【解决方案1】:

检查您的分隔符是否实际上是一个制表符 ('\t') 而不是通常的逗号 (',') 或空格 (' ')。 如果是这两个中的任何一个,则需要相应地更改第二行。

【讨论】:

  • 我唯一能想到的另一件事是“text”还有一个像空格这样的字符:“text”。
猜你喜欢
  • 2021-04-11
  • 2020-01-23
  • 2017-12-29
  • 2022-12-17
  • 2022-01-12
  • 2018-07-05
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多