csv有字母怎么轉(zhuǎn)換成數(shù)字?
最簡單的方法是使用str.split方法對每次出現(xiàn)的'進(jìn)行拆分,并將每個(gè)字符串映射到strip方法以刪除任何前導(dǎo)/后綴空格。例如,>>> s = "1, John Doe, Boston, USA"
>>> print map(str.strip, s.split(','))
['1', 'John Doe', 'Boston', 'USA']
如果您有包含多行csv的多行字符串,則可以在\ n上分割,然后分割并剝離每行。例如,>>> s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA"
>>> print [map(str.strip, s_inner.split(',')) for s_inner in s.splitlines()]
[['1', 'John Doe', 'Boston', 'USA'], ['2', 'Jane Doe', 'Chicago', 'USA']]
Python中的csv模塊還具有一個(gè)輔助功能,閱讀器可實(shí)現(xiàn)相同的結(jié)果。例如,>>> s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines()
>>> import csv
>>> x = csv.reader(s)
>>> list(x)
[['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]