简体   繁体   English

Python 使用正则表达式搜索 CSV 并将结果导出到不同的 CSV

[英]Python Search CSV with Regex and export result to different CSV

I am using Python3 with the regex and csv module loaded, and trying to create a script to pull a string out of a csv with a regular expression and then export the result it to a different csv.我正在使用加载了 regex 和 csv 模块的 Python3,并尝试创建一个脚本以使用正则表达式从 csv 中提取字符串,然后将结果导出到不同的 csv。 The idea is i have a csv that someone gave me that has a single columned and for some reason has a cell with way to much infomation in it.这个想法是我有一个有人给我的 csv,它有一个单列,并且由于某种原因有一个包含很多信息的单元格。 including quotes, line return, and bunch of other garbage.包括引号、换行符和一堆其他垃圾。 I only need a very small section of each cell.我只需要每个单元格的一小部分。

My script is able to print the result but for some reason the following script returns the error "AttributeError: 're.Match' object has no attribute 'write'" when trying to writerow to the csv.我的脚本能够打印结果,但由于某种原因,以下脚本在尝试向 csv "AttributeError: 're.Match' object has no attribute 'write'"返回错误"AttributeError: 're.Match' object has no attribute 'write'"

I want to extract a single string from each cell of the csv and then export it to another csv.我想从 csv 的每个单元格中提取一个字符串,然后将其导出到另一个 csv。

import csv
import re

with open('Failed.csv',mode='r') as csv_file, open('result.csv', mode='wb') as csv_result:
     csv_reader = csv.reader(csv_file)
     writer=csv.writer(csv_result, delimiter=',')
     for row in csv_reader:
            pattern = 'Computer Configuration\\.*\n*.*'
            currentrow = row[0]
            found = re.search(pattern, currentrow) 
            if found:
                print(found)
                writer.writerow(found)

The method re.search returns a Match object that you can't use directly.方法re.search返回一个您不能直接使用的Match对象。 If you want to retrieve a valu from the row you may use a group如果你想从行中检索一个值,你可以使用一个组

value = "foo123"
pattern = "foo(.*)"
match = re.search(pattern, value)

print(match, type(match))  # <re.Match object; span=(0, 3), match='foo'> <class 're.Match'>
print(match.groups())  # ('123',)
print(match.group(1))  # 123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM