为了账号安全,请及时绑定邮箱和手机立即绑定

引号与某些字符串一起出现,而不是其他字符串。如何使所有字符串都相同?

引号与某些字符串一起出现,而不是其他字符串。如何使所有字符串都相同?

皈依舞 2021-07-26 17:49:39
我正在将 csv 文件读入字典,根据需要转换数据,并将其写入新的 csv 文件。原始 csv 文件有一列,其中一些字符串(单词)在双引号中,而其他字符串不在引号中。像这样:FOODS;CALS"PIZZA";600"PIZZA";600"BURGERS";500"PIZZA";600PASTA;400"PIZZA";600SALAD;100CHICKEN WINGS;300"PIZZA";600"PIZZA";600在我将此列写入我的输出文件后,它看起来像下面的数组,原始 CSV 中带引号的单词现在周围有三个引号,其他没有:FAVORITE_FOOD;VOTES"""PIZZA""";6"""BURGERS""";1PASTA;1SALAD;1CHICKEN WINGS;1我需要删除引号,所以我的最终 csv 看起来像这样:FAVORITE_FOOD;VOTESPIZZA;6BURGERS;1PASTA;1SALAD;1CHICKEN WINGS;1这是我在文件中阅读的方式:with open(input_data_txt, "r") as file:    # This enables skipping the header line.    skipped = islice(file, 1, None)    for i, line in enumerate(skipped, 2):        try:            food, cals = line.split(';')        except ValueError:            pass这是我的写作方式:with open(food_txt, 'w') as myfile:    wr = csv.writer(myfile, delimiter=';')    for i in final_array:        wr.writerow(i)
查看完整描述

3 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

三重引号可能由csv模块添加以转义现有引号。

所以而不是像这样的东西:

csvwriter.writeline(food, vote)

尝试类似:

csvwriter.writeline(food.strip('"'), vote)


查看完整回答
反对 回复 2021-08-03
?
慕森卡

TA贡献1806条经验 获得超8个赞

您可以使用csv.DictReader以便按名称collections.Counter对列进行寻址,使用 a来计算每种食物出现的次数,然后使用相应csv.writer地输出它们,例如:


import csv

from collections import Counter


with open('input_file') as fin, open('output_file', 'wb') as fout:

    # Count occurrences of each FOODS type

    votes = Counter(row['FOODS'] for row in csv.DictReader(fin, delimiter=';'))

    # Create a csv.writer around the output file and write the header columns

    csvout = csv.writer(fout, delimiter=';')

    csvout.writerow(['FAVORITE_FOOD', 'VOTES'])

    # Write the name and vote counts to the file

    csvout.writerows(votes.items())


查看完整回答
反对 回复 2021-08-03
  • 3 回答
  • 0 关注
  • 182 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号