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']]