我熟悉R数据持有者,如矢量,数据帧等,但需要进行一些文本分析,看起来python有一些很好的设置.我的问题是我在哪里可以找到python如何保存数据的解释.
具体来说,我在一个制表符分隔的文件中有一个数据集,其中文本在第3列,我需要的数据的评分在第4列.
id1 id2 text score
123 889 "This is the text I need to read..." 88
234 778 "This is the text I need to read..." 78
345 667 "This is the text I need to read..." 91
Run Code Online (Sandbox Code Playgroud)
在R中我只是将它加载到一个名为的数据框中df1,当我想调用一个列时,我会使用df1 $ text或者df1[,3] 如果我想要一个特定的单元格,我可以使用它df1[1,3].
我对如何将数据读入python而不是如何处理类似结构的表格有所了解.
你会如何建议为一个python新手使用它?
我不确定这会转化为我从未使用过的'R',但在Python中,这就是我接近它的方式:
lines = list()
with open('data.txt','r') as f:
for line in f:
lines.append(line.split())
Run Code Online (Sandbox Code Playgroud)
这将读取python列表中的所有内容.列表从零开始.要从第二行获取文本列:
print lines[1][2]
Run Code Online (Sandbox Code Playgroud)
该行的得分:
print lines[1][3]
Run Code Online (Sandbox Code Playgroud)
除了Panda的DataFrame,您还可以使用rpy2库(来自http://thread.gmane.org/gmane.comp.python.rpy/1344):
import array
import rpy2.robjects as ro
d = dict(x = array.array('i', [1,2]), y = array.array('i', [2,3]))
dataf = ro.r['data.frame'](**d)
Run Code Online (Sandbox Code Playgroud)
我过去使用的一个选项是csv.DictReader,它允许您按名称引用行中的数据(每行变为a dict):
import csv
with open('data.txt') as f:
reader = csv.DictReader(f, delimiter = '\t')
for row in reader:
print row
Run Code Online (Sandbox Code Playgroud)
输出:
{'text': 'This is the text I need to read...', 'score': '88', 'id2': '889', 'id1': '123'}
{'text': 'This is the text I need to read...', 'score': '78', 'id2': '778', 'id1': '234'}
{'text': 'This is the text I need to read...', 'score': '91', 'id2': '667', 'id1': '345'}
Run Code Online (Sandbox Code Playgroud)