<p>Python语法错误-CSV文件输入:
我正在尝试对一个实现使用CSV屏蔽测试,并从<a href="https://districtdatalabs.silvrback.com/a-practical-guide-to-anonymizing-<a href="https://www.cnpython.com/pypi/dataset" class="inner-link">dataset</a>s-with-python-faker" rel="nofollow noreferrer">masking using faker</a>获取用例。从链接中获取示例代码并尝试执行该程序。但是我在访问csv文件时遇到语法错误。在</p>
<pre><code>import unicodecsv as csv
from faker import Factory
from collections import defaultdict
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.
names = defaultdict(faker.name)
emails = defaultdict(faker.email)
# Iterate over the rows and yield anonymized rows.
for row in rows:
# Replace the name and email fields with faked fields.
row['name'] = names[row['name']]
row['email'] = emails[row['email']]
# Yield the row back to the caller
yield row
def anonymize('masktest.csv', 'masktest_tgt.csv'):
"""
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.
"""
with open('masktest.csv', 'rU') as f:
with open('masktest_tgt.csv', '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):
print (row['name'])
writer.writerow(row)
</code></pre>
<p>在</p>
^{pr2}$