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

时间:2018-10-30 09:00:43

标签: python arrays csv quotation-marks

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

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

赞:

public LayerClass DrawString(LayerClass.Type _text, string text, RectangleF rect, Font _fontStyle, PaintEventArgs e)
{
    using (StringFormat string_format = new StringFormat())
    {
        rect.Size = e.Graphics.MeasureString(text, _fontStyle);
        rect.Location = new PointF(Shape.center.X - (rect.Width / 2), Shape.center.Y - (rect.Height / 2));
        if(isOutlinedOrSolid)
        {
            using (GraphicsPath path = new GraphicsPath())
            {
                path.AddString(text, _fontStyle.FontFamily, (int)_fontStyle.Style, rect.Size.Height, rect, string_format);
                e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
                e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
                e.Graphics.CompositingMode = CompositingMode.SourceOver;
                e.Graphics.DrawPath(new Pen(Color.Red, 1), path);
            }
        }
        else
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            e.Graphics.CompositingMode = CompositingMode.SourceOver;
            e.Graphics.DrawString(text,_fontStyle,Brushes.Red, rect.Location);
        }
    }

    this._Text = text;
    this._TextRect = rect;
    return new LayerClass(_text, this, text, rect);
}

在将此列写入输出文件之后,它看起来像下面的数组,其中原始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

这是我在文件中读取的方式:

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

3 个答案:

答案 0 :(得分:1)

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

所以不是这样的:

csvwriter.writeline(food, vote)

尝试类似的东西:

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

答案 1 :(得分:0)

使用replace

file = open(r"PY.csv")
text = file.read()
text = text.split()
for i in range(len(text)):
    text[i] = text[i].replace('"',"")

比您将有一个这样的列表:

PIZZA
PIZZA
BURGERS
PIZZA
PASTA
PIZZA
SALAD
CHICKEN WINGS
PIZZA
PIZZA

答案 2 :(得分:0)

您可以使用csv.DictReader,以便可以按名称寻址列,collections.Counter可以对每种食物的出现次数进行计数,然后使用{{1} }进行相应的输出,例如:

csv.writer