python - AttributeError:“dict”对象没有属性“split”
问题描述
我正在尝试运行此代码,其中字典的数据保存在单独的 csv 文件中。这是字典:
body = {
'dont-ask-for-email': 0,
'action': 'submit_user_review',
'post_id': 76196,
'email': email_random(),
'subscribe': 1,
'previous_hosting_id': prev_hosting_comp_random(),
'fb_token': '',
'title': review_title_random(),
'summary': summary_random(),
'score_pricing': star_random(),
'score_userfriendly': star_random(),
'score_support': star_random(),
'score_features': star_random(),
'hosting_type': hosting_type_random(),
'author': name_random(),
'social_link': '',
'site': '',
'screenshot[image][]': '',
'screenshot[description][]': '',
'user_data_process_agreement': 1,
'user_email_popup': '',
'subscribe_popup': 1,
'email_asked': 1
}
现在这是写入 CSV 文件并最终保存的代码:
columns = []
rows = []
chunks = body.split('}')
for chunk in chunks:
row = []
if len(chunk)>1:
entry = chunk.replace('{','').strip().split(',')
for e in entry:
item = e.strip().split(':')
if len(item)==2:
row.append(item[1])
if chunks.index(chunk)==0:
columns.append(item[0])
rows.append(row)
df = pd.DataFrame(rows, columns = columns)
df.head()
df.to_csv ('r3edata.csv', index = False, header = True)
但这是我得到的错误:
Traceback (most recent call last):
File "codeOffshoreupdated.py", line 125, in <module>
chunks = body.split('}')
AttributeError: 'dict' object has no attribute 'split'
我知道 dict 没有名为 split 的属性,但我该如何解决?
编辑:我想要的 CSV 格式:
dont-ask-for-email, action, post_id, email, subscribe, previous_hosting_id, fb_token, title, summary, score_pricing, score_userfriendly, score_support, score_features, hosting_type,author, social_link, site, screenshot[image][],screenshot[description][],user_data_process_agreement,user_email_popup,subscribe_popup,email_asked
0,'submit_user_review',76196,email_random(),1,prev_hosting_comp_random(),,review_title_random(),summary_random(),star_random(),star_random(),star_random(),star_random(),hosting_type_random(),name_random(),,,,,1,,1,1
注意:所有提到的这些函数都是返回值
编辑2:
我从 email_random() 函数中挑选电子邮件,如下所示:
def email_random():
with open('emaillist.txt') as emails:
read_emails = csv.reader(emails, delimiter = '\n')
return random.choice(list(read_emails))[0]
emaillist.txt 是这样的:
xyz@gmail.com
xya@gmail.com
xyb@gmail.com
xyc@gmail.com
xyd@gmail.com
其他功能也从这样的文件中提取数据。
解决方案
由于body
是字典,因此您无需进行任何手动解析即可将其转换为 CSV 格式。
如果您希望将函数调用(如email_random()
)这样写入 CSV,则需要将它们包含在引号中(如下所示)。如果您希望它们解析为函数调用并写入结果,则可以保持原样。
import csv
def email_random():
return "john@example.com"
body = {
'dont-ask-for-email': 0,
'action': 'submit_user_review',
'post_id': 76196,
'email': email_random(),
'subscribe': 1,
'previous_hosting_id': "prev_hosting_comp_random()",
'fb_token': '',
'title': "review_title_random()",
'summary': "summary_random()",
'score_pricing': "star_random()",
'score_userfriendly': "star_random()",
'score_support': "star_random()",
'score_features': "star_random()",
'hosting_type': "hosting_type_random()",
'author': "name_random()",
'social_link': '',
'site': '',
'screenshot[image][]': '',
'screenshot[description][]': '',
'user_data_process_agreement': 1,
'user_email_popup': '',
'subscribe_popup': 1,
'email_asked': 1
}
with open('example.csv', 'w') as fhandle:
writer = csv.writer(fhandle)
items = body.items()
writer.writerow([key for key, value in items])
writer.writerow([value for key, value in items])
我们在这里做的是:
with open('example.csv', 'w') as fhandle:
example.csv
这将打开一个具有写入权限 ( )的新文件 (名为)'w'
并将引用存储到变量fhandle
中。如果您对使用with
不熟悉,您可以从这个 PEP中了解更多关于它们的信息。
body.items()
将返回一个可迭代的元组(这样做是为了保证字典项以相同的顺序返回)。这个的输出看起来像[('dont-ask-for-email', 0), ('action', 'submit_user_review'), ...]
。
然后,我们可以首先使用列表推导式写入所有键,然后在下一行写入所有值。
这导致
dont-ask-for-email,action,post_id,email,subscribe,previous_hosting_id,fb_token,title,summary,score_pricing,score_userfriendly,score_support,score_features,hosting_type,author,social_link,site,screenshot[image][],screenshot[description][],user_data_process_agreement,user_email_popup,subscribe_popup,email_asked
0,submit_user_review,76196,john@example.com,1,prev_hosting_comp_random(),,review_title_random(),summary_random(),star_random(),star_random(),star_random(),star_random(),hosting_type_random(),name_random(),,,,,1,,1,1
推荐阅读
- python - 屏蔽数组以计算 2 个条件内的值
- c++ - 为什么我的代码在 micopython env 中出错,而不是在使用 g++ 编译时出错
- amazon-web-services - 火花提交泊坞窗图像?
- autodesk-forge - Forge Viewer:为每个模型打开“显示边缘”而不是全局设置
- javascript - 如何检查一个项目是否存在于动态数组中?
- python - 如何在两个图表之间切换并保持单选按钮和滑块更新正常工作?
- datetime - 什么是未将时区转换为 UTC 的 UNIX 纪元格式的日期格式?
- .net - 在 ASP.Net 中使用 Azure.Storage.Queues - 为 DI 配置
- java - MultipartUtility 类的本地实例在 java 中是线程安全的吗?
- javascript - 单击按钮并将文件内容下载到 JavaScript 变量