如何从给定参数的csv文件中提取特定数据?

2024-04-30 04:38:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从给定的csv文件(到一个单独的.txt文件)中提取中性词,但我对python还比较陌生,对文件处理不太了解。我找不到中性词的数据集,但是在到处搜索之后,我找到了这个。在

下面是我要从中提取数据的Gtihub项目(以防万一有人需要知道):hoffman-prezioso-projects/Amazon_Review_Sentiment_Analysis

Neutral Words
Word     Sentiment Score
a        0.0125160264947
the      0.00423728459134
it      -0.0294755274737
and      0.0810574365028
an       0.0318918766949
or      -0.274298468178
normal  -0.0270787859177

所以基本上我只想从csv中提取数值为0的单词(文本)。在


Tags: 文件csv数据项目txtamazonanalysisreview
3条回答

即使不使用任何库,使用csv也相当容易。在

首先打开该文件(我假设您在变量filename中保存了路径),然后使用readlines()函数读取该文件,然后根据您给出的条件过滤掉。在

with open(filename, 'r') as csv:                         # Open the file for reading
    rows = [line.split(',') for line in csv.readlines()] # Read each the file in lines, and split on commas
    filter = [line[0] for line in rows if abs(float(line[1])) < 1]   
                                                         # Filter out all lines where the second value is not equal to 1

这是公认的答案,所以我添加了一个免责声明。有许多原因说明,不应该毫无考虑地将此代码应用于其他csv。在

  • 它读取内存中的整个CSV
  • 它不包括引用

对于非常简单的CSV来说这是可以接受的,但是如果您不能确定CSV不会破坏这段代码,那么这里的其他答案会更好。在

像这样使用熊猫:

import pandas
df = pandas.read_csv("yourfile.csv")
df.columns = ['word', 'sentiment']

按情选词:

^{pr2}$

这里有一种方法可以只使用普通lib而不将整个文件保存在内存中

import csv

def get_vals(filename):
    with open(filename, 'rb') as fin:
        reader = csv.reader(fin)
        for line in reader:
            if line[-1] <= 0:
                yield line[0]

words = get_vals(filename)

for word in words:
    do stuff...

相关问题 更多 >