猿问

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

我正在将 csv 文件读入字典,根据需要转换数据,并将其写入新的 csv 文件。


原始 csv 文件有一列,其中一些字符串(单词)在双引号中,而其他字符串不在引号中。


像这样:


FOODS;CALS

"PIZZA";600

"PIZZA";600

"BURGERS";500

"PIZZA";600

PASTA;400

"PIZZA";600

SALAD;100

CHICKEN WINGS;300

"PIZZA";600

"PIZZA";600

在我将此列写入我的输出文件后,它看起来像下面的数组,原始 CSV 中带引号的单词现在周围有三个引号,其他没有:


FAVORITE_FOOD;VOTES

"""PIZZA""";6

"""BURGERS""";1

PASTA;1

SALAD;1

CHICKEN WINGS;1

我需要删除引号,所以我的最终 csv 看起来像这样:


FAVORITE_FOOD;VOTES

PIZZA;6

BURGERS;1

PASTA;1

SALAD;1

CHICKEN 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)


皈依舞
浏览 183回答 3
3回答

至尊宝的传说

三重引号可能由csv模块添加以转义现有引号。所以而不是像这样的东西:csvwriter.writeline(food, vote)尝试类似:csvwriter.writeline(food.strip('"'), vote)

慕森卡

您可以使用csv.DictReader以便按名称collections.Counter对列进行寻址,使用 a来计算每种食物出现的次数,然后使用相应csv.writer地输出它们,例如:import csvfrom collections import Counterwith 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())
随时随地看视频慕课网APP

相关分类

Python
我要回答