Python CSV 问题

标签 python csv

我第一次在将 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,父级,名称,\n 部分,无,美国,\n 部分,无,欧洲,\n 部分,无,亚洲,\n 部分,无,非洲,\n 国家、美国、美国\n 国家/地区、美国、阿根廷、\n 国家/地区,美国,巴哈马,\n 国家/地区,美国,玻利维亚,\n 国家/地区、美国、巴西、\n 国家/地区,美国,哥伦比亚,\n 国家/地区、美国、加拿大、\n 国家/地区,美国,开曼群岛,\n 国家、美国、智利、\n 国家/地区,美国,哥斯达黎加,\n 国家/地区,美国,多米尼加共和国,\n 我已经阅读了很多有关 csv 的内容,尝试了导入 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'

最佳答案

首先,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 中,以解析制表符分隔的文件。

关于Python CSV 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584332/

相关文章:

python - FastAPI 处理和重定向 404

python - 使用 Python 工厂习语

python - 在 python/pyqt 中有效编辑大型 csv 文件的某些记录

arrays - F# CSV - 为每一行从列数据创建一个数组

java - 如何将 CSV 文件解码为 java 对象

python TfidfVectorizer 给出 typeError : expected string or bytes-like object on csv file

从存储的 MySQL 过程中导出 PHP CSV

python - Pytorch:具有沿多个轴的张量的索引或一次分散到多个索引

python - 如何将文件名传递给从 Python 执行的外部命令?

python - 在 Django 中使用 Cython。是否有意义?