简体   繁体   English

仅使用python中的csv阅读器读取csv文件的前N行

[英]only reading first N rows of csv file with csv reader in python

I'm adding the text contained in the second column of a number of csv files into one list to later perform sentiment analysis on each item in the list. 我正在将多个csv文件的第二列中包含的文本添加到一个列表中,以便稍后对列表中的每个项目执行情感分析。 My code is fully working for large csv files at the moment, but the sentiment analysis I'm performing on the items in the list takes too long which is why I want to only read the first 200 rows per csv file. 目前,我的代码已完全适用于大型csv文件,但是我对列表中的项目进行的情感分析花费的时间太长,这就是为什么我只想读取每个csv文件的前200行的原因。 The code looks as follows: 该代码如下所示:

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))

How do I make sure to only read over the first 200 rows per csv file with the csv reader? 如何确保仅使用csv阅读器读取每个csv文件的前200行?

The shortest and most idiomatic way is probably to use itertools.islice : 最简短,最惯用的方式可能是使用itertools.islice

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

You can just add a count, and break when in reaches 200, or add a loop with a range of 200. 您可以添加一个计数,然后在达到200时中断,或者添加一个range为200的循环。

Define a variable right before your for loop for row s starts: row s row的for循环开始之前定义一个变量:

count = 0

Then inside your loop: 然后在循环中:

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

Using readlines() should do it. 使用readlines()应该可以做到。

with open(item, encoding = 'latin-1').readlines()[0: 199] as d:
    reader1=csv.reader(d)

Pandas is a popular module for manipulating data, like CSVs. Pandas是用于处理数据(例如CSV)的流行模块。 Using pandas this is how you could limit the number of rows. 使用大熊猫可以限制行数。

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

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

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