0

我正在尝试使用 Python 用 CSV 中的“DMD”替换某个列(例如第 6 列“作者”)中的空白值。我对这个程序还很陌生,所以很多术语都会让我感到困惑。我已通读 CSV Python 文档,但似乎没有任何特定于我的问题的内容。这是我到目前为止所拥有的。它不运行。我收到错误“dict”对象没有属性替换。似乎在字典中应该有类似的替换。另外,我不完全确定我搜索该字段的方法是否准确。任何指导将不胜感激。

import csv
inputFileName = "C:\Author.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_edited.csv"

field = ['Author']

with open(inputFileName) as infile, open(outputFileName, "w") as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, field)
    w.writeheader()
    for row in r:
        row.replace(" ","DMD")
        w.writerow(row)
4

4 回答 4

1

我觉得你很接近。您需要将字段名传递给writer然后您可以row直接编辑,因为它只是一个字典。例如:

with open(inputFileName, "rb") as infile, open(outputFileName, "wb") as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, r.fieldnames)
    w.writeheader()
    for row in r:
        if not row["Author"].strip():
            row["Author"] = "DMD"
        w.writerow(row)

转弯

a,b,c,d,e,Author,g,h
1,2,3,4,5,Smith,6,7
8,9,10,11,12,Jones,13,14
13,14,15,16,17,,18,19

进入

a,b,c,d,e,Author,g,h
1,2,3,4,5,Smith,6,7
8,9,10,11,12,Jones,13,14
13,14,15,16,17,DMD,18,19

我喜欢使用if not somestring.strip():,因为那样的话,如果没有空格,或者一个,或者十七个和一个制表符,都没有关系。我也更喜欢DictReader标准阅读器,因为这样您就不必记住Author所在的列。

[PS:以上假设 Python 2,而不是 3。]

于 2013-04-29T16:28:43.547 回答
0

字典不需要该replace方法,因为简单的赋值会为您执行此操作:

for row in r:
    if row[header-6] == "":
        row[header-6] = "DMD"
    w.writerow(row)

header-6你的第六栏的名字在哪里

另请注意,您的调用DictReader似乎具有错误的fields属性。该参数应该是一个列表(或其他序列),按顺序包含新 CSV 的所有标题。

出于您的目的,使用香草阅读器似乎更简单:

import csv
inputFileName = "C:\Author.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_edited.csv"

with open(inputFileName) as infile, open(outputFileName, "w") as outfile:
    r = csv.reader(infile)
    w = csv.writer(outfile)
    w.writerow(next(r))  # Writes the header unchanged
    for row in r:
        if row[5] == "":
            row[5] = "DMD"
        w.writerow(row)
于 2013-04-29T16:11:04.643 回答
0

(1) 要使用 os.path.splitest,需要添加一个import os

(2) dicts没有replace方法;dicts 不是字符串。如果您尝试更改作为 dict 条目值的字符串,则需要按键引用该 dict 条目,例如row['Author']. 如果 row['Author'] 是一个字符串(应该是你的情况),你可以对其进行替换。听起来您需要 Python 词典的介绍,例如参见http://www.sthurlow.com/python/lesson06/

(3) 一种方法,也可以处理字段中的多个空格、无空格等,如下所示:

field = 'Author'
marker = 'DMD'
....

## longhand version
candidate = str(row[field]).strip()
if candidate:
    row[field] = candidate
else:
    row[field] = marker

或者

## shorthand version
row[field] = str(row[field]).strip() and str(row[field]) or marker

干杯

于 2013-04-29T16:41:39.697 回答
0
with open('your file', 'r+') as f2:
    txt=f2.read().replace('@','').replace("'",'').replace('"','').replace('&','')
    f2.seek(0)
    f2.write(txt)
    f2.truncate()

保持简单并替换您选择的字符。

于 2022-03-05T07:16:05.367 回答