简体   繁体   English

在python中分隔CSV列

[英]separating columns CSV in python

how to separate this line, I need just the numbers 如何分隔这行,我只需要数字

PD-1358 393;

I would like to increment a variable X and a Y 我想增加一个变量X和Y

 X   Y
PD-1358 393;

I am using the CSV command (csv_file, delimiter='-') but I can not separate these numbers. 我正在使用CSV命令(csv_file, delimiter='-')但无法分隔这些数字。 Can anybody help me? 有谁能够帮助我?

import csv

with open('circulo.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='-')

    line_count = 0
    for row in csv_reader:

         print(f'\t {row[0]}')

For the moment I've only been able to separate this part 目前,我只能将这部分分开

Using regex you can simply do: 使用正则表达式,您可以简单地执行以下操作:

import re

re.findall(r'\d+', "PD-1358 393") 

Result: 结果:

['1358', '393']

Don't know of an easy way to do this, but assuming you've turned the data into a string like so: 不知道执行此操作的简单方法,但是假设您已将数据转换为如下所示的字符串:

s = 'PD-1358 393'

Then create a generator to go to the first instance of a digit: 然后创建一个生成器以转到数字的第一个实例:

i = next((index for (index,value) in enumerate(s) if value.isdigit()))

And then split: 然后拆分:

s[i:].split()

Returns: 返回值:

['1358', '393']

If you want numbers in the final array: 如果要在最终数组中输入数字:

line = 'PD-1358 393;'

parts = line.split(' ')

numbers = [int(''.join(i for i in part if i.isdigit())) for part in parts]

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

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