我怎么能从csv读取列

时间:2014-01-16 20:34:15

标签: python python-2.7 csv python-3.x

    a=['Business', 'Food/Clothes', 'Fun', 'Politics', 'Starting_with_Apolog', ['NNP', 'MD', 'NN', 'NNP'], ['NNP', 'NN', 'NNP'], ['PDT', 'MD', 'NN', 'NNP'], ['PRP$', 'MD', 'NN', 'NNP'], ['UH', 'MD', 'NN', 'NNP'], ['WP$', 'MD', 'NN', 'NNP'], 'end__with_ly', 'end_with_al', 'end_with_ful', 'end_with_ible', 'end_with_ic', 'end_with_ive', 'end_with_less', 'end_with_ous', 'sorry_word', 'Gender']

    f = open("file.csv")
    reader = csv.reader(f)
    headers = None
    results = []
    for row in reader:
        if not headers:
            headers = []
            for i, col in enumerate(row):
                if col in a:
                    # Store the index of the cols of interest
                    headers.append(i)
            print headers     
        else:
            results.append(list([row[i] for i in headers]))
    return results

上面的代码是从 file.csv 中读取列表 a 中的特定列,因此结果将在结果中可用,但索引代码只会索引以下列:

** Fun 63
** Food/Clothes 64
** Politics 70
** Business 73
** end_with_al 75
** end_with_ful 76
** end_with_ible 77
** end_with_ic 78
** end_with_ive 79
** end_with_less 80
** end__with_ly 81
** end_with_ous 82
** sorry_word 83
** Starting_with_Apolog 84
** Gender 1487

代码不会对列表中的列表编制索引 - 如何让代码也搜索它们? 注意:file.csv包含一些包含1487列的数据; a 包含file.csv中的一些列。

2 个答案:

答案 0 :(得分:1)

为什么不删除列表中的列表?

实施例

'Starting_with_Apolog', ['NNP', 'MD', 'NN', 'NNP']

更改为:

'Starting_with_Apolog', 'NNP', 'MD', 'NN', 'NNP'

这是一个简单的黑客攻击,但它可能是最简单的方法。

修改

好的,因为你想把列表留在列表结构中,我相信你将不得不放弃一些性能。我可以考虑解决它的下一个最简单的方法如下:

a=['Business', 'Food/Clothes', 'Fun', 'Politics', 'Starting_with_Apolog', ['NNP', 'MD', 'NN', 'NNP'], ['NNP', 'NN', 'NNP'], ['PDT', 'MD', 'NN', 'NNP'], ['PRP$', 'MD', 'NN', 'NNP'], ['UH', 'MD', 'NN', 'NNP'], ['WP$', 'MD', 'NN', 'NNP'], 'end__with_ly', 'end_with_al', 'end_with_ful', 'end_with_ible', 'end_with_ic', 'end_with_ive', 'end_with_less', 'end_with_ous', 'sorry_word', 'Gender']
newa = []    
for element in a:
    if isinstance(element, list):
        for el in element:
            newa.append(el)
    else:
        newa.append(element)
a = newa
# Now use "a" or "newa" in the rest of your code.

否则你的if col in a:支票会变得更加复杂......

希望这有帮助!

答案 1 :(得分:0)

您的问题是,in不会自动测试是否包含在a的子列表中。

>>> 'Fun' in a
    True
>>> 'NNP' in a
    False

>>> 'NNP' in a[5] #a[5] is the list ['NNP', 'MD', 'NN', 'NNP']
    True