2014-09-28 54 views
0

我有單元格中帶有製表符分隔數字的csv文件。Python:將csv行中的所有值轉換爲編號

我想將行中的所有值轉換爲數組中的數字。

例如: 輸入:

1 2 3 4 
0 1 1 3 

輸出:

[1234, 0113] 

怎麼辦呢?

+1

你想讓'0113'成爲什麼數字? – 2014-09-28 16:05:11

+0

您的輸入看起來不像CSV文件。你可能只是想刪除所有的空間? – 5gon12eder 2014-09-28 16:05:58

+0

5gon12eder,是的,我想刪除所有\ t – bdhvevhvonof 2014-09-28 16:08:44

回答

0

你做需要re,只是splitstr.join並映射到int

with open("in.txt") as f: 
    nums = map(int,("".join(x.rstrip().split()) for x in f)) 

使用或不使用map

[int(s) for s in (x.rstrip().replace(" ","") for x in f)] 

的文件用100行:

In [49]: %%timeit 
with open("in.txt") as f: 
    nums = map(int,("".join(x.rstrip().split()) for x in f)) 
    ....: 
10000 loops, best of 3: 140 µs per loop 

In [50]: %%timeit 
with open('in.txt', 'r') as istr: 
    lines = [re.sub(r'\s*', '', line) for line in istr] 
    [int(n) for n in lines] 
    ....: 
1000 loops, best of 3: 519 µs per loop 

In [53]: %%timeit 
    ....: with open("in3.txt") as f: 
    ....:  nums = [int(s) for s in (x.rstrip().replace(" ","") for x in f)] 
    ....: 
10000 loops, best of 3: 127 µs per loop 
0

如果你想從每行刪除所有空格,你可以使用正則表達式:

import re 

lines = list() 
with open('input.txt', 'r') as istr: 
    for line in istr: 
     line = re.sub(r'\s*', '', line) 
     lines.append(line) 

或者,如果你喜歡它的功能:

import re 

with open('input.txt', 'r') as istr: 
    lines = [re.sub(r'\s*', '', line) for line in istr] 

注意上面的例子會給你一個字符串列表。如果你想將它們轉換爲整數,你可以將int內置函數映射到它。

numbers = [int(n) for n in lines] 
+0

爲什麼地球上,你需要一個正則表達式? – 2014-09-28 16:42:11

+0

@PadraicCunningham總有不止一種方法可以做到這一點。我認爲正則表達式是一種合理的方式。 (它的優點是它可以很好地擴展到分隔符比空格多的情況,比如'\ s *,\ s *'。)'split()'和'join()'是另一個。我想我們可以想出更多的解決方案。 – 5gon12eder 2014-09-28 17:07:38

+0

我認爲在這種情況下,一個簡單的製表符分隔的文件沒有遠程複雜的模式,使用正則表達式不是要走的路,也不會鼓勵任何人開始在這種情況下使用正則表達式。 – 2014-09-28 17:10:36