我正在使用 Python 3 使用 Faker 包来屏蔽数据集。我在以下网址获得了一个代码: http ://blog.districtdatalabs.com/a-practical-guide-to-anonymizing-datasets-with-python-faker 。
代码:
def anonymize_rows(rows):
"""
Rows is an iterable of dictionaries that contain name and
email fields that need to be anonymized.
"""
# Load the faker and its providers
faker = Factory.create()
# Create mappings of names & emails to faked names & emails.
c1 = defaultdict(faker.CARD_NO_ID)
c2 = defaultdict(faker.ISS_USER_NAME)
# Iterate over the rows and yield anonymized rows.
for row in rows:
# Replace the name and email fields with faked fields.
row['CARD_NO_ID'] = c1[row['CARD_NO_ID']]
row['ISS_USER_NAME'] = c2[row['ISS_USER_NAME']]
# Yield the row back to the caller
yield row
"""
The source argument is a path to a CSV file containing data to
anonymize, while target is a path to write the anonymized CSV data to.
"""
source = 'card_transaction_data_all.csv'
target = 'card_transaction_data_all_fake.csv'
with open(source, 'rU') as f:
with open(target, 'w') as o:
# Use the DictReader to easily extract fields
reader = csv.DictReader(f)
writer = csv.DictWriter(o, reader.fieldnames)
# Read and anonymize data, writing to target file.
for row in anonymize_rows(reader):
writer.writerow(row)
但我不断收到如下错误:
C:\Anaconda3.4\lib\site-packages\spyderlib\widgets\externalshell\start_ipython_kernel.py:1: DeprecationWarning: 'U' mode is deprecated # - - coding: utf-8 - - Traceback (最近一次调用最后) :
文件“”,第 5 行,在 writer = csv.DictWriter(o, reader.fieldnames)
文件“C:\Anaconda3.4\lib\csv.py”,第 96 行,字段名 self._fieldnames = next(self.reader)
文件“C:\Anaconda3.4\lib\site-packages\unicodecsv\py3.py”,第 55 行,在下一个 返回 self.reader。下一个()
文件“C:\Anaconda3.4\lib\site-packages\unicodecsv\py3.py”,第 51 行,在 f = (bs.decode(encoding, errors=errors) for bs in f)
AttributeError:“str”对象没有属性“decode”
有人可以帮我在 Python 3 中实现代码吗?非常感谢。