2016-11-07 25 views
-1

驗證CSV文件中的所有列的數據類型我有CSV文件這樣通過UNIX

dsdgh|234|@jhsjdh||jdhjdhfu|123| 
#45ghf|123|laiej|||b8#hfj| 
|hyrhyf|123||fhyr|@#$%| 

等。

列數可以等於100.上面的文件也是管道分離的。

我要檢查每列的數據類型,即一列是否是數字或字母或字母

,並希望重定向結果txt文件

請幫幫我,要達到這個

感謝

+0

是每一行中的列數一樣嗎? – qzb

+0

是的沒有。每列都相同 – Chandan

回答

0

假設在列的每一行數是一樣的,你可以使用這個腳本:

import re 
import sys 

input_file = open(sys.argv[1]) 

cols = None 

for line in input_file.readlines(): 
    fields = line.split('|') 

    if not cols: 
     cols = map(lambda _: 'empty', fields) 

    for i, field in enumerate(fields): 
     if field == '': 
      continue 

     if re.match(r'^[0-9]+$', field): 
      if cols[i] == 'empty': 
       cols[i] = 'numeric' 
      elif cols[i] == 'alphabetic': 
       cols[i] = 'alphanumeric' 
     elif re.match(r'^[^0-9]+$', field): 
      if cols[i] == 'empty': 
       cols[i] = 'alphabetic' 
      if cols[i] == 'numeric': 
       cols[i] = 'alphanumeric' 
     else: 
      cols[i] = 'alphanumeric' 

print '|'.join(cols) 

只是保存到文件(script.py在這個例子中),然後運行:

$ python script.py <path_to_file_with_columns> 
+0

感謝您的幫助,但是我需要unix中的上述腳本 – Chandan

+0

* Unix *是一種操作系統,不是編程語言。 python解釋器可用於大多數posix兼容系統,包括Linux和OSX。如果你想使用shell腳本來實現,你應該在你的問題中包含這些信息。 – qzb

+0

yes unix是操作系統,但我不想在python中使用此解決方案,我有另一個shell腳本,我只想將上述問題的解決方案添加到該shell腳本中 – Chandan