如何将Python的csv字符串转换为数组?
在本文中,我们将了解如何将CSV字符串转换为数组。
第一种方法是使用`split()`方法。此方法接受一个参数,并指定应在哪个字符处分割字符串的分隔符。由于输入是csv,它是逗号分隔的,因此我们将分隔符设置为逗号,并将字符串分割成数组。
Python中的`split()`方法是一个字符串操作函数,它将较长的字符串分割成多个较短的字符串。`split()`方法将字符串作为列表返回。
示例
在下面的示例中,我们采用CSV字符串作为输入,并将其转换为数组。
str1 = "Hello,Everyone,Welcome,to,Tutorialspoint"
print("The given CSV string is")
print(str1)
print("Converting the given CSV string into array")
res = list(map(str.strip, str1.split(',')))
print(res)
输出
上述示例的输出如下:
The given CSV string is Hello,Everyone,Welcome,to,Tutorialspoint Converting the given CSV string into array ['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']
使用`inner.split()`和`splitlines()`
第二种方法是使用`inner.split()`和`splitlines()`。如果输入的CSV字符串是多行的,则使用此方法。在这种情况下,我们首先应该分割行,因此我们将使用`splitlines()`方法在新行字符处进行分割。在新行分割后,我们应该使用`inner.split()`方法在逗号处分割每一行,然后我们将它们组合成单个列表。
示例
在下面的示例中,我们采用多行CSV字符串作为输入,并使用`inner.split()`和`splitlines()`将其转换为数组。
s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA"
print("The given CSV string is")
print(s)
print("Converting the given CSV string into array")
res = list(map(str.strip, s_inner.split(',')) for s_inner in s.splitlines())
print((res))
输出
上述示例的输出如下:
The given CSV string is 1, John Doe, Boston, USA 2, Jane Doe, Chicago, USA Converting the given CSV string into array [<map object at 0x7f8074f002b0>, <map object at 0x7f8074f00390>]
使用csv库的`reader()`方法
第三种方法是使用csv库的`reader()`方法。此方法采用CSV字符串作为输入,并将其转换为数组。此方法也可用于多行输出,但我们必须使用`splitlines()`方法转换多行。
示例
在下面的示例中,我们采用CSV字符串作为输入,并使用`reader()`方法将其转换为数组。
import csv
str1 = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines()
print("The given CSV string is")
print(str1)
print("Converting the given CSV string into array")
x = csv.reader(str1)
print(list(x))
输出
上述示例的输出如下:
The given CSV string is ['1, John Doe, Boston, USA', '2, Jane Doe, Chicago, USA'] Converting the given CSV string into array [['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP