【问题标题】:how can i read column from csv我如何从 csv 读取列
【发布时间】:2014-01-16 20:34:14
【问题描述】:
    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 中的一些列。

【问题讨论】:

  • 您确定使用细分隔符吗?
  • a中的子列表有什么意义?

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


【解决方案1】:

为什么不直接删除列表里面的列表呢?

例子

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

改为:

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

这是一个简单的 hack,但它可能是最简单的方法。

编辑

好的,既然您想将列表保留在列表结构中,我相信您将不得不放弃一些性能。下面列出了我能想到的下一个最简单的解决方法:

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: 支票会变得更加复杂...

希望这会有所帮助!

【讨论】:

    【解决方案2】:

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

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

    但是

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

    【讨论】:

    • @Dylan 我想要的是列表
    • def try_literal_eval(item): try: return ast.literal_eval(item) except (SyntaxError, ValueError): return item a = [try_literal_eval(item=str(item).replace(" "," ")) for item in class_label] print 打印一个包含列表的实际 class_label...所以我如何使用 a[i] 进行搜索
    猜你喜欢
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多