【问题标题】:only reading first N rows of csv file with csv reader in python仅在 python 中使用 csv reader 读取前 N 行 csv 文件
【发布时间】:2018-11-02 13:18:39
【问题描述】:

我正在将多个 csv 文件的第二列中包含的文本添加到一个列表中,以便稍后对列表中的每个项目执行情绪分析。我的代码目前完全适用于大型 csv 文件,但我对列表中的项目执行的情绪分析需要太长时间,这就是为什么我只想读取每个 csv 文件的前 200 行。代码如下:

import nltk, string, lumpy 
import math
import glob
from collections import defaultdict
columns = defaultdict(list)
from nltk.corpus import stopwords
import math
import sentiment_mod as s
import glob

lijst = glob.glob('21cf/*.csv')

tweets1 = []
for item in lijst:
    stopwords_set = set(stopwords.words("english"))
    with open(item, encoding = 'latin-1') as d:
        reader1=csv.reader(d)
        next(reader1)
        for row in reader1:
            tweets1.extend([row[2]])
        words_cleaned = [" ".join([words for words in sentence.split() if 'http' not in words and not words.startswith('@')]) for sentence in tweets1]
        words_filtered = [e.lower() for e in words_cleaned]
        words_without_stopwords = [word for word in words_filtered if not word in stopwords_set]
    tweets1 = words_without_stopwords
    tweets1 = list(filter(None, tweets1))

如何确保使用 csv 阅读器仅读取每个 csv 文件的前 200 行?

【问题讨论】:

  • 为什么不简单地添加一个具有所需范围的 for 循环?
  • 你总是可以像this question那样使用熊猫

标签: python csv


【解决方案1】:

最短最惯用的方式大概就是使用itertools.islice

import itertools
...
        for row in itertools.islice(reader1, 200):
            ...

【讨论】:

    【解决方案2】:

    Pandas 是一种流行的数据处理模块,例如 CSV。使用 pandas 可以限制行数。

    import pandas as pd
    # If you only want to read the first 200 (non-header) rows:
    pd.read_csv(..., nrows=200)
    

    【讨论】:

      【解决方案3】:

      您可以只添加一个计数,并在达到 200 时中断,或者添加一个带有 200 的 range 的循环。

      rows 的 for 循环开始之前定义一个变量:

      count = 0
      

      然后在你的循环中:

      count = count + 1
      if count == 200: 
          break
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-14
        • 2017-10-31
        • 2019-10-09
        • 2023-01-25
        • 2016-12-06
        • 2017-12-07
        • 2015-10-23
        • 2011-08-12
        相关资源
        最近更新 更多