获取lis中单词的CSV值

2024-09-24 22:17:59 发布

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

我试图找出如何将文本文件中的标记与excel文件中的数据进行比较。 我把文本转换成一个元组列表,我可以从csv文件中读取数据,看起来像这样(但要大得多):

      name   score1   score2   score3
      arm    1        2        3
      beard  4        5        6
      chin   7        8        9

我把文本变成了一个元组列表,看起来像这样:

[(0, 'My'), (1, 'arm'), (2, 'has'), (3, 'no'), (4, 'chin'), (5, '.')]

我想做的是迭代数据文件中的名称,返回相应的分数并从中创建一个新列表:

[(0, 'My'), (1, 'arm', 1, 2, 3), (2, 'has'), (3, 'no'), (4, 'chin', 7, 8, 9), (5, '.')]

我能读出某一行的分数

import pandas as pd
data = pd.read_csv('datafile.csv')    
names = data[:1][['score1', 'score2', 'score3']]

我还可以检查这些名称中的特定单词:

names.str.contains("arm")

我现在的问题是,我既不知道如何检索非特定名称(不仅仅是data[:1])的分数,也不知道如何检索iterable变量的分数。我也不知道如何在我的文本中检查任何字符串。你知道吗

编辑更改了csv文件


Tags: 文件csv文本名称列表datamy分数
1条回答
网友
1楼 · 发布于 2024-09-24 22:17:59

您的用例非常简单,我建议不要使用外部库(当然除了漂亮的打印…)。你知道吗

代码被注释,它产生的输出也被注释。。。你知道吗

from pprint import pprint as pp

# you don't need to store the ordering in a list,
# because lists are ordered by their nature 
text = ['My', 'arm', 'has', 'no', 'chin', '.']
print 'Text to annotate'
pp(text)

# slurp the data, throw away the header, split on whitespace
data = [row.split() for row in open('datafile.csv').readlines()[1:]]
print '\nData as a list of rows'
pp(data)

# turn into a dictionary with lists of ints
data = {row[1]:[int(elt) for elt in row[2:]] for row in data}
print '\nData as a dictionary of lists of scores'
pp(data)

annotated_text = [tuple([word]+data[word]) if word in data else (word,)
                  for word in text]
print '\nAnnotated text'
pp(annotated_text)
print '\nNB: the order of the words in the text is preserved in the annotated text.'

将上述内容保存到一个文件中并执行,得到了以下oputput

Text to annotate
['My', 'arm', 'has', 'no', 'chin', '.']

Data as a list of rows
[['0', 'arm', '1', '2', '3'],
 ['1', 'beard', '4', '5', '6'],
 ['2', 'chin', '7', '8', '9']]

Data as a dictionary of lists of scores
{'arm': [1, 2, 3], 'beard': [4, 5, 6], 'chin': [7, 8, 9]}

Annotated text
[('My',), ('arm', 1, 2, 3), ('has',), ('no',), ('chin', 7, 8, 9), ('.',)]

NB: the order of the words in the text is preserved in the annotated text.

编辑:显示预期输出的交互式会话

我删去了评论和大部分打印件。你知道吗

% cat test1.py
text = ['My', 'arm', 'has', 'no', 'chin', '.']
data = [row.split() for row in open('datafile.csv').readlines()[1:]]
data = {row[0]:[int(elt) for elt in row[1:]] for row in data}
annotated_text = [tuple([w]+data[w]) if w in data else (w,) for w in text]
print annotated_text
% cat datafile.csv 
       name   score1   score2   score3
       arm    1        2        3
       beard  4        5        6
       chin   7        8        9
% python test1.py 
[('My',), ('arm', 1, 2, 3), ('has',), ('no',), ('chin', 7, 8, 9), ('.',)]
% 

相关问题 更多 >