【问题标题】:Python 2.7 Can't Write out file from DictReader with DictWriter after re.findall with RegexPython 2.7 无法在使用正则表达式 re.findall 后使用 DictWriter 从 DictReader 中写出文件
【发布时间】:2016-05-13 16:14:32
【问题描述】:

我已经尝试了许多基于伟大的堆栈溢出想法的方法:

How to write header row with csv.DictWriter?

Writing a Python list of lists to a csv file

csv.DictWriter -- TypeError: __init__() takes at least 3 arguments (4 given)

Python: tuple indices must be integers, not str when selecting from mysql table

https://docs.python.org/2/library/csv.html

python csv write only certain fieldnames, not all

Python 2.6 文本处理和

Why is DictWriter not Writing all rows in my Dictreader instance?

我尝试映射读取器和写入器字段名以及特殊的标头参数。

我根据一些很棒的多栏 SO 文章构建了第二层测试:

代码如下

import csv
import re
t = re.compile('<\*(.*?)\*>')
headers = ['a', 'b', 'd', 'g']
with open('in2.csv', 'rb') as csvfile:
    with open('out2.csv', 'wb') as output_file:
        reader = csv.DictReader(csvfile)
        writer = csv.DictWriter(output_file, headers, extrasaction='ignore')
        writer.writeheader()
        print(headers)
        for row in reader:
            row['d'] = re.findall(t, row['d'])
            print(row['a'], row['b'], row['d'], row['g'])
            writer.writerow(row)

输入数据是:

a, b, c, d, e, f, g, h 

<* number 1 *>, <* number 2 *>, <* number 3 *>, <* number 4 *>, ...<* number 8 *> 

<* number 2 *>, <* number 3 *>, <* number 4 *>, ...<* number 8 *>, <* number 9 *> 

输出数据为:

['a', 'b', 'd', 'g' ] 

('<* number 1 *>', '<* number 2 *>', ' number 4 ', <* number 7 *>) 

('<* number 2 *>', '<* number 3 *>', ' number 5 ', <* number 8 *>) 

完全符合要求。

但是,当我使用包含空格、双引号和混合大小写字母的单词的更粗略的数据集时,打印在行级别上工作,但书写不完全工作。

总的来说,我已经能够(我知道我在这里处于史诗般的失败模式)实际编写了一行具有挑战性的数据,但在这种情况下,一个标题和多行却不行。我读过的所有有才华的文章都无法克服这个障碍,这真是太蹩脚了。

所有四列都因键错误或“TypeError:元组索引必须是整数,而不是 str”而失败

我显然不明白如何掌握 Python 需要什么来实现这一点。

高级是:读取具有七个观察值/列的文本文件。只用四栏写出来;在一列上执行正则表达式。确保写出每个新形成的行,而不是原始行。

我可能需要一种更友好的全局临时表类型来读取行,更新行,然后将行写出到文件中。

也许我对 Python 架构的要求太多,以协调 DictReader 和 DictWriter 来读取数据、过滤到四列、用正则表达式更新第四列,然后用更新的四个元组写出文件。

此时,我没有时间研究解析器。我想最终更详细地介绍一下,因为每个 Python 版本(现在是 2.7,以后是 3.x)解析器似乎很方便。

再次对这种方法的复杂性以及我对 Python 基础知识缺乏了解表示歉意。在 R 语言中,与我的缺点相似的是理解 S4 级别的编码,而不仅仅是 S3 级别。

这是更接近失败的数据,抱歉--我需要展示如何设置标题,如何使用单个双引号对传入的文件行进行格式化,并在整行周围加上引号以及日期如何已格式化,但未引用:

    stuff_type|stuff_date|stuff_text
""cool stuff"|01-25-2015|""the text stuff <*to test*> to find a way to extract all text that is <*included in special tags*> less than star and greater than star"""
""cool stuff"|05-13-2014|""the text stuff <*to test a second*> to find a way to extract all text that is <*included in extra special tags*> less than star and greater than star"""
""great big stuff"|12-7-2014|"the text stuff <*to test a third*> to find a way to extract all text that is <*included in very special tags*> less than star and greater than star"""
""nice stuff"|2-22-2013|""the text stuff <*to test a fourth ,*> to find a way to extract all text that is <*included in doubly special tags*> less than star and greater than star"""

stuff_type,stuff_date,stuff_text
cool stuff,1/25/2015,the text stuff <*to test*> to find a way to extract all text that is <*included in special tags*> less than star and greater than star
cool stuff,5/13/2014,the text stuff <*to test a second*> to find a way to extract all text that is <*included in extra special tags*> less than star and greater than star
great big stuff,12/7/2014,the text stuff <*to test a third*> to find a way to extract all text that is <*included in very special tags*> less than star and greater than star
nice stuff,2/22/2013,the text stuff <*to test a fourth *> to find a way to extract all text that is <*included in really special tags*> less or greater than star

我打算重新测试这个,但是今天早上 Spyder 的更新导致我的 Python 控制台崩溃了。呃。使用 vanilla Python,上面的测试数据失败并显示以下代码...无需执行写入步骤...甚至无法在此处打印...可能需要方言中的 QUOTES.NONE。

import csv
import re 
t = re.compile('<\*(.*?)\*>')
headers = ['stuff_type', 'stuff_date', 'stuff_text']
with open('C:/Temp/in3.csv', 'rb') as csvfile:
    with open('C:/Temp/out3.csv', 'wb') as output_file:
        reader = csv.DictReader(csvfile)
        writer = csv.DictWriter(output_file, headers, extrasaction='ignore')
        writer.writeheader()
        print(headers)
        for row in reader:
            row['stuff_text'] = re.findall(t, row['stuff_text'])
            print(row['stuff_type'], row['stuff_date'], row['stuff_text'])
            writer.writerow(row)

错误:

这里的截图工具图片无法通过....抱歉

KeyError: 'stuff_text'

好的:它可能在列的引用和分隔中:上面没有引号的数据在没有 KeyError 的情况下打印,现在可以正确写入文件:我可能必须先从引号字符中清理文件,然后再用正则表达式。任何想法将不胜感激。

好问题@Andrea Corbellini

如果我手动删除了引号,上面的代码会生成以下输出:

stuff_type,stuff_date,stuff_text
cool stuff,1/25/2015,"['to test', 'included in special tags']"
cool stuff,5/13/2014,"['to test a second', 'included in extra special tags']"
great big stuff,12/7/2014,"['to test a third', 'included in very special tags']"
nice stuff,2/22/2013,"['to test a fourth ', 'included in really special tags']"

这就是我想要的输出。所以,谢谢你的“懒惰”问题——我是懒惰的人,应该把第二个输出放在后面。

同样,在不删除多组引号的情况下,我有 KeyError: 'stuff_type'。很抱歉,我试图从带有错误的 Python 屏幕截图中插入图像,但尚未弄清楚如何在 SO 中执行此操作。我使用了上面的图像部分,但这似乎指向一个可能上传到 SO 的文件?没有插入?

@monkut 在下面关于使用“.”的出色输入。加入事物或字面上的东西变得更好。

{['stuff_type', 'stuff_date', 'stuff_text']
('cool stuff', '1/25/2015', 'to test:included in special tags')
('cool stuff', '5/13/2014', 'to test a second:included in extra special tags')
('great big stuff', '12/7/2014', 'to test a third:included in very special tags')
('nice stuff', '2/22/2013', 'to test a fourth :included in really special tags')}
    
import csv
import re 
t = re.compile('<\*(.*?)\*>')
headers = ['stuff_type', 'stuff_date', 'stuff_text']
csv.register_dialect('piper', delimiter='|', quoting=csv.QUOTE_NONE)
with open('C:/Python/in3.txt', 'rb') as csvfile:
    with open('C:/Python/out5.csv', 'wb') as output_file:
        reader = csv.DictReader(csvfile, dialect='piper')
        writer = csv.DictWriter(output_file, headers, extrasaction='ignore')
        writer.writeheader()
        print(headers)
        for row in reader:
            row['stuff_text'] = ":".join(re.findall(t, row['stuff_text']))
            print(row['stuff_type'], row['stuff_date'], row['stuff_text'])
            writer.writerow(row)

错误路径如下:

runfile('C:/Python/test quotes with dialect quotes none or quotes filter and special characters with findall regex.py', wdir='C:/Python')
['stuff_type', 'stuff_date', 'stuff_text']
('""cool stuff"', '01-25-2015', 'to test')
Traceback (most recent call last):

  File "<ipython-input-3-832ce30e0de3>", line 1, in <module>
    runfile('C:/Python/test quotes with dialect quotes none or quotes filter and special characters with findall regex.py', wdir='C:/Python')

  File "C:\Users\Methody\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)

  File "C:\Users\Methody\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Python/test quotes with dialect quotes none or quotes filter and special characters with findall regex.py", line 20, in <module>
    row['stuff_text'] = ":".join(re.findall(t, row['stuff_text']))

  File "C:\Users\Methody\Anaconda\lib\re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)

TypeError: expected string or buffer

在处理正则表达式 findall 之前,我将找到一种更强大的方法来清理和删除引号。可能是 row = string.remove(quotes with blanks)。

【问题讨论】:

  • 请原谅我的懒惰:我只阅读了您问题的 10%。您能否只显示代码以及产生问题的输入、预期输出和实际输出?
  • 您的 KeyError 表明您在输入 in3.csv 文件中没有“stuff_text”列。
  • @monkut:明白你在说什么,但是有一个名为“stuff_text”的列标题。但是,你比你想象的更正确......进来的数据行是在被读入字典之前不会分解为数据元素的字符串。如果我消除字符串上的引号,这将有效。将在运行正则表达式之前测试 row.replace 引号。我最好不要与字符串的不变性作斗争。如果引号仍在图片中,则标题未与 dict 数据元素对齐。
  • @monkut,不要犹豫,纠正我讨论 Python 内部的尝试;请不要假设我关于数据元素的术语是正确的——我很想在理论关系代数 C.J. Date 中使用 Python 特定的术语元组,有点意思。数据元素试图描述 DictReader 和 DictWriter JSON。
  • 在这里,您的 TypeError 是由于将已编译的正则表达式对象提供给 findall, try, t.findall(row['stuff_text'])。

标签: python regex


【解决方案1】:

我认为 findall 返回一个列表,这可能会把事情搞砸,因为 dictwriter 想要一个字符串值。

row['d'] = re.findall(t, row['d'])

您可以使用 .join 将结果转换为单个字符串值:

row['d'] = ":".join(re.findall(t, row['d']))

这里的值是用“:”连接的。不过,正如您所提到的,您可能需要进一步清理这些值...

您提到使用已编译的正则表达式对象存在问题。 下面是一个如何使用已编译的正则表达式对象的示例:

import re
t = re.compile('<\*(.*?)\*>')
text= ('''cool stuff,1/25/2015,the text stuff <*to test*> to find a way to extract all text that'''
       ''' is <*included in special tags*> less than star and greater than star''')
result = t.findall(text)

这应该将以下内容返回到result

['要测试', '包含在特殊标签中']

【讨论】:

  • 当我把引号拉出来时,它起作用了……那是我的作弊……使用不带引号的 Excel csv 与带有很多引号的记事本文本文件,这通常是我处理的和。感谢您,monkut,花时间考虑一下:我认为您在某些方面是对的:re.findall 需要比我想象的更干净的数据才能返回一个好的列表项。
  • 不带引号,这里是添加了 ":".join 的结果,请参阅上面问题中格式化的输出。
猜你喜欢
  • 2018-10-12
  • 2021-09-30
  • 1970-01-01
  • 2012-02-18
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2014-10-27
  • 2017-09-20
相关资源
最近更新 更多