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

2024-09-24 04:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我不知道如何实现目前。我需要根据两列中的匹配数据从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将根据城市名称与第二列以及第九列中的名称匹配来删除一行。

我希望这是一个相对简单的功能。如果有人能提供一个如何做到这一点的例子,将不胜感激。谨致问候


Tags: csv数据名称newjohnsmith文本文件london
1条回答
网友
1楼 · 发布于 2024-09-24 04:21:14

这里有一个例子。它假定csv文件名为'输入.csv'并写入文件'输出.csv“与‘巴黎’、‘特雷弗·威尔逊’不匹配的行。”。在

它使用来自itertools docsgrouper配方将行组合成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('')

相关问题 更多 >