我试图重写一些csv读取代码,以便能够在Python 3.2.2的多个内核上运行它.我try 使用多处理的Pool对象,这是我根据工作示例改编的(并且已经为我的项目的另一部分工作过).我遇到了一条错误信息,我发现很难破译和排除故障.

错误是:

Traceback (most recent call last):
  File "parser5_nodots_parallel.py", line 256, in <module>
    MG,ppl = csv2graph(r)
  File "parser5_nodots_parallel.py", line 245, in csv2graph
    node_chunks)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/multiprocessing/pool.py", line 251, in map
    return self.map_async(func, iterable, chunksize).get()
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/multiprocessing/pool.py", line 552, in get
    raise self._value
AttributeError: __exit__

相关代码:

import csv
import time
import datetime
import re
from operator import itemgetter
from multiprocessing import Pool
import itertools

def chunks(l,n):
    """Divide a list of nodes `l` in `n` chunks"""
    l_c = iter(l)
    while 1:
        x = tuple(itertools.islice(l_c,n))
        if not x:
            return
        yield x

def csv2nodes(r):
    strptime = time.strptime
    mktime = time.mktime
    l = []
    ppl = set()
    pattern = re.compile(r"""[A-Za-z0-9"/]+?(?=[,\n])""")
    for row in r:
        with pattern.findall(row) as f:
            cell = int(f[3])
            id = int(f[2])
            st = mktime(strptime(f[0],'%d/%m/%Y'))
            ed = mktime(strptime(f[1],'%d/%m/%Y'))
        # collect list
        l.append([(id,cell,{1:st,2: ed})])
        # collect separate sets
        ppl.add(id)
    return (l,ppl)

def csv2graph(source):
    MG=nx.MultiGraph()
    # Remember that I use integers for edge attributes, to save space! Dic above.
    # start: 1
    # end: 2
    p = Pool()
    node_divisor = len(p._pool)
    node_chunks = list(chunks(source,int(len(source)/int(node_divisor))))
    num_chunks = len(node_chunks)
    pedgelists = p.map(csv2nodes,
                       node_chunks)
    ll = []
    ppl = set()
    for l in pedgelists:
        ll.append(l[0])
        ppl.update(l[1])
    MG.add_edges_from(ll)
    return (MG,ppl)

with open('/Users/laszlosandor/Dropbox/peers_prisons/python/codetenus_test.txt','r') as source:
    r = source.readlines()
    MG,ppl = csv2graph(r)

解决这个问题的好方法是什么?

推荐答案

问题在于:

with pattern.findall(row) as f:

您使用的是with语句.它需要一个包含__enter____exit__个方法的对象.但是pattern.findall返回一个listwithtry 存储__exit__方法,但找不到它,并引发一个错误.使用

f = pattern.findall(row)

相反

Python-3.x相关问答推荐

一种基于绝对排序值的极框索引和列定位的Python方法

如何在python中有效地使用多处理和pytube库来加快下载速度?

像计数不显示在html和想知道如果我的模型设置正确

以编程方式关闭jupyterlab内核

在循环中使用Print&S结束参数时出现奇怪的问题

基于另一个数据帧计算总和

检测点坐标 - opencv findContours()

如何在 20 秒后重复使用 Pillow 在现有图像上创建新图像?

!date 的命令无法从 jupyter notebook 运行

过滤阈值大小数据以使用 Pyspark 或 Python 读取

通过附加/包含多个列表来创建 nDimensional 列表

Dask worker post-processing

Python从base64转换为二进制

二进制文件的 Python 3 和 base64 编码

Pytorch 的随机 Select ?

Python3 的超级和理解-> TypeError?

在 Alembic 迁移期间更新列内容

Python pathlib 获取父级相对路径

如何判断列表中的所有项目是否都是字符串

python中的绝对导入是什么?