简体   繁体   English

如何使用python删除csv文件中逗号前后的间隔?

[英]How do I remove spaced before and after commas in a csv file using python?

Currently one row of my csv file looks like this : 目前我的csv文件的一行如下所示:

314523, 165538, 76255, 335416, 416827 1250536:1 1744638:1 298526:1 1568238:1 314523,165538,76255,335416,416827 1250536:1 1744638:1 298526:1 1568238:1

I need it to look like this : 我需要它看起来像这样:

314523,165538,76255,335416,416827 1250536:1 1744638:1 298526:1 1568238:1 314523,165538,76255,335416,416827 1250536:1 1744638:1 298526:1 1568238:1

I only want to remove the spaces after or before commas and leave the other blank spaces as it is. 我只想删除逗号之后或之前的空格,并保留其他空格。

How can I do this in python? 我怎么能在python中这样做?

Note : I am a beginner in python 注意:我是python的初学者

I would recommend using the replace function. 我建议使用替换功能。 You enter the pattern you want to replace. 您输入要替换的模式。 In your example, the pattern is comma space (', ') and space comma (' ,') . 在您的示例中,模式是逗号空格(', ')和空格逗号(' ,') Then say what you want to replace the pattern with (',') . 然后说出你要用(',')替换模式的内容。

line=line.replace(', ', ',').replace(' ,',',')

You can use regex to do this, for a string: 对于字符串,您可以使用正则表达式执行此操作:

import re
outputstring = re.sub(r'\s*,\s*', ',', inputstring)

This regex matches the whitespace surrounding a comma and the comma, and replaces it with just a comma. 这个正则表达式匹配逗号和逗号周围的空白,并用逗号替换它。 For a file, just do this for each line. 对于文件,只需对每行执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM