Python 使用文本文件中的数据交叉匹配和删除csv中的行

Python 使用文本文件中的数据交叉匹配和删除csv中的行,python,csv,python-2.7,text,matching,Python,Csv,Python 2.7,Text,Matching,我有一个问题,我不知道如何实现目前。我需要根据两列中的匹配数据从csv中删除行 因此,如果文本文件读取: London James Smith, John Oliver, John-Smith-Harrison Paris Hermione, Trevor Wilson New York city Charlie Chaplin, Ned Stark, Thoma' Becket, Ryan-Dover 然后csv将根据城市名称与第二列以及第九列中的名称的匹配删除一行 我希望这是一个相对简

我有一个问题,我不知道如何实现目前。我需要根据两列中的匹配数据从csv中删除行

因此,如果文本文件读取:

London
James Smith, John Oliver, John-Smith-Harrison

Paris
Hermione, Trevor Wilson

New York city
Charlie Chaplin, Ned Stark, Thoma' Becket, Ryan-Dover
然后csv将根据城市名称与第二列以及第九列中的名称的匹配删除一行


我希望这是一个相对简单的函数。如果有人能提供一个如何做到这一点的例子,将不胜感激。这是一个例子。它假定csv文件名为“input.csv”,并将与“Paris”、“Trevor Wilson”不匹配的行写入文件“output.csv”

它使用来自的
grouper
配方将行组合为3组

请注意,由于没有定义良好的标准,csv文件的语法差别很大。如果您的实际输入文件与您发布的示例不匹配,那么值得查看
csv
模块的文档。例如,我使用了
skipinitialspace
选项告诉解析器忽略分隔符后面的空白

import csv
from itertools import *

# see recipies section in itertools docs
# http://docs.python.org/2/library/itertools.html
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

with open('input.csv') as f:
    data = csv.reader(f, skipinitialspace=True)
    with open('output.csv', 'w') as output_f:
        output = csv.writer(output_f)
        for city, names, blank in grouper(data, 3, []):
            if not (city[0] == 'Paris' and 'Trevor Wilson' in names):
                output.writerow(city)
                output.writerow(names)
                output.writerow('')