【问题标题】:Python CSV proplemPython CSV 问题
【发布时间】:2015-11-07 15:19:51
【问题描述】:

我第一次遇到将 csv 加载到 Python 中的问题。

我正在尝试做this。我的 csv 文件与他的相同,但更长且值不同。

当我运行它时,

import collections
path='../data/struc.csv'
answer = collections.defaultdict(list)
with open(path, 'r+') as istream:
    for line in istream:
        line = line.strip()
        try:
            k, v = line.split(',', 1)
            answer[k.strip()].append(v.strip())
        except ValueError:
            print('Ignoring: malformed line: "{}"'.format(line))

print(answer)

一切运行良好。我得到了你所期望的。

如果没有从link 复制和粘贴代码,在这两种情况下都会出错。

在接受的答案中,终端返回 ValueError: need more than 1 value to unpack

在第二个答案中,我得到 AttributeError: 'file' object has no attribute 'split'。如果您调整它以获取列表,它也不起作用。

我觉得问题出在 csv 文件本身。它的头是

_id,parent,name,\n Section,none,America's,\n Section,none,Europe,\n Section,none,Asia,\n Section,none,Africa,\n Country,America's,United States,\n Country,America's,Argentina,\n Country,America's,Bahamas,\n Country,America's,Bolivia,\n Country,America's,Brazil,\n Country,America's,Colombia,\n Country,America's,Canada,\n Country,America's,Cayman Islands,\n Country,America's,Chile,\n Country,America's,Costa Rica,\n Country,America's,Dominican Republic,\n 我已经阅读了很多关于 csv 的内容,尝试了 import csv 的内容,但仍然没有运气。 请有人帮忙。遇到这种问题是最糟糕的。

import re
from collections import defaultdict

parents=defaultdict(list)
path='../data/struc.csv'

with open(path, 'r+') as istream:
    for i, line in enumerate(istream.split(',')):
        if i != 0 and line.strip():
            id_, parent, name = re.findall(r"[\d\w-]+", line)
            parents[parent].append((id_, name))



Traceback (most recent call last):

  File "<ipython-input-29-2b2fd98946b3>", line 1, in <module>
runfile('/home/bob/Documents/mega/tree/python/structure.py',       wdir='/home/bob/Documents/mega/tree/python')

  File "/home/bob/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)

   File "/home/bob/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
    builtins.execfile(filename, *where)

  File "/home/bob/Documents/mega/tree/python/structure.py", line 15, in <module>
    for i, line in enumerate(istream.split(',')):

AttributeError: 'file' object has no attribute 'split'

【问题讨论】:

  • 您能准确地向我们展示您正在运行的代码,以及错误的完整堆栈跟踪吗?
  • 一方面,您在 , 上进行拆分,但 CSV 文件中没有。
  • @Kenney,感谢您的回复。是逗号分隔的,只是我从liboffice复制粘贴过来的
  • @TomDalton 感谢您的回复。我刚刚发布了链接中的第二个,我尝试了多种获取文件的组合,这只是最新的。所有错误都出现在同一行。
  • 另外,在上面的代码中,` ','` 已经绝望地尝试过了。我也用过'\n'

标签: python csv


【解决方案1】:

首先,Python 的标准库中有一个特殊模块,用于处理不同风格的 CSV。参考documentation

当 CSV 文件有标题时,csv.DictReader 可能是更直观的解析文件的方式:

import collections
import csv

filepath = '../data/struc.csv'
answer = collections.defaultdict(list)

with open(filepath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        answer[row["_id"].strip()].append(row["parent"].strip())

print(answer)

您可以通过标题中的名称来引用行中的字段。这里我假设你想使用 _id 和 parent,但你明白了。

另外,dialect=csv.excel_tab 可以作为参数添加到 DictReader 以解析制表符分隔的文件。

【讨论】:

  • 谢谢,我会阅读 csv 的所有文档。输出是我需要的。是像你这样的人让像我这样的哀悼者可以编程。
【解决方案2】:

如果您打算对这些数据进行任何分析,那么我建议您学习 pandas 库。 Pandas 库会处理所有似乎让您感到困惑的细节,让打开 csv 文件变得简单。

import pandas as pd
csv_file = pd.read_csv(file_path)

【讨论】:

  • 这就是我通常加载它的方式,这使一切变得更容易。不过我并没有对其进行分析,我正在尝试制作一个 json 树
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2010-11-15
  • 2018-01-25
  • 2019-10-13
  • 1970-01-01
  • 2021-11-28
  • 2016-10-08
相关资源
最近更新 更多