更改行数据以防不匹配

2024-03-29 10:10:40 发布

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

我在尝试使用CSV文件时遇到了一个问题。基本上,我有一个包含名称和ID的CSV文件。头文件类似于:

新ID |名称|需要更改的ID |名称|

在列[0]的新ID列中,有从1到980的数字。在[3]列中,需要更改的ID有714个。我真正需要完成的是创建列[4],它将存储来自列[1]的ID,以防在列[3]中找到列[1]中的名称。我需要找到一个函数,它将从列[1]中选取1个名称,扫描整个列[3]以查看该名称是否存在,如果存在,则将列[0]中的ID复制到列[4]

到目前为止我得到了这个:

import csv
input = open('tbr.csv', "rb")
output = open('sortedTbr.csv',  "wb")
reader = csv.reader(input)
writer = csv.writer(output)

for row in input:
    writer.writerow(row)
    print row

input.close
output.close

这没什么用。它将每个字母写入csv中的一个新列。。。你知道吗


Tags: 文件csv函数名称idcloseinputoutput
1条回答
网友
1楼 · 发布于 2024-03-29 10:10:40

这里有三个问题:

  • 首先不指定分隔符,我假设它是管道。csv分析器无法自动检测分隔符。你知道吗
  • 第二,创建读取器,但扫描原始输入文件, 这就解释了当你写回csv时,它会创建尽可能多的单元格(以string类型而不是list类型遍历行)
  • 第三,当您关闭句柄时,实际上并不调用close,而只是访问方法引用。添加()来调用这些方法(典型的错误,每个人都会偶尔被抓住)

这是我对你的“扩展”问题的修正版本。你需要两个通行证,一个完全阅读第1列,另一个检查。我使用dict来存储值,并在名称和ID之间建立关系

我的代码仅在Python2.7中运行,但在Python3.4中运行,前提是您对所示行进行注释/取消注释

import csv
# python 2 only, remove if using python 3:
input_handle = open('tbr.csv', "r")  # don't use input: reserved kw    
output = open('sortedTbr.csv',  "wb")
# uncomment 2 lines below if you're using python 3
#input_handle = open('tbr.csv', "r", newline='')  # don't use input: reserved kw
#output = open('sortedTbr.csv',  "w", newline='')

reader = csv.reader(input_handle,delimiter='\t')
writer = csv.writer(output,delimiter='\t')

title = next(reader) # skip title line
title.append("ID2")  # add column title

db = dict()

input_rows = list(reader)  # read file once
input_handle.close()   # actually calls close!

# first pass
for row in input_rows:
    db[row[1]] = row[0] # relation: name => id

writer.writerow(title)

# second pass
for row in input_rows:
    row.append(db.get(row[3],""))

    writer.writerow(row)

output.close()

我将其用作tbr.csv(应该是.tsv,因为分隔符是TAB)

New ID  name    ID that needs to be changed name
492 abboui jaouad jordan    438 abboui jaouad jordan
22  abrazone nelli  536 abrazone nelli
493 abuladze damirs 736 abuladze damirs
275 afanasjeva ludmila  472 afanasjeva oksana
494 afanasjeva oksana   578 afanasjevs viktors
54  afanasjevs viktors  354 aksinovichs andrejs
166 aksinovichs andrejs 488 aksinovichs german
495 aksinovichs german  462 aleksandra 

在输出中得到这个:注意:添加了一列

New ID  name    ID that needs to be changed name    ID2
492 abboui jaouad jordan    438 abboui jaouad jordan    492
22  abrazone nelli  536 abrazone nelli  22
493 abuladze damirs 736 abuladze damirs 493
275 afanasjeva ludmila  472 afanasjeva oksana   494
494 afanasjeva oksana   578 afanasjevs viktors  54
54  afanasjevs viktors  354 aksinovichs andrejs 166
166 aksinovichs andrejs 488 aksinovichs german  495
495 aksinovichs german  462 aleksandra 

我想说这是可行的。不要犹豫接受答案:)

相关问题 更多 >