2016-07-04 278 views
0

在CSV搜索我使用Python 3.5.x的解析和蟒蛇

在Python中我试图解析其中有很多paragrah在它和身份的csv文件,并得到几场比赛中,创造新的csv文件出它

让成像我有2行,但在实际时间将有更多的行

描述。

Welcom new joinee User1. your initial login id : and you get access to Depart "Accounting" applciation. with below access 

     acount user1 access modify 
     account user1 access readonly 

Thank you. any issue contact helpdesk 

Welcom new joinee User2. your initial login id : and you get access to Depart "Finance" Applciation. with below access 

      acount user2 access write 
      account user2 access read 

Thank you. any issue contact helpdesk 

现在我用“re.search”得到我想要什么,并存储在一个vailable

例子让我们来想象,我用re.search并获得3以下的比赛,并在变量存储成功

row 1 
     user_name =User1 
     Departement = Accounting 
     account =User1 
     access = modify and readyonly 

row 2 
     user_name =User2 
     Departement = Finance 
     account =User 
     access = write and read 

我理想中的CSV文件看起来像下面

Accounting,user1|modify\nuser1|readonly 
Finance ,User2|write\nuser2|Modify 

注意:有'|'作为分隔符,“\ n”作为user_name和访问valiables换行符”

而是我所得到的是像在错误的道路这

Accounting,user1|modify\nuser1|readonly\nFinance,User2|write\nuser2|Modify 

下面是我的代码。我可能会做soemthing。任何更好的的方式来实现我的结果

import csv 
import re 
import string 
file =open('test_input.csv','r') 
out_file=open('test_out.csv','w') 
lines = file.readlines() 
for x in lines : 
    app_name=re.search('-------',x) 
    user_name=re.search('------',x) 
    department=re.search('......',x) 
    account=re.search('----',x) 
    access=re.search('-----',x) 
    if user_name: 
     e= user_name.group(1).strip() 
     e=e+"," 
     out_file.write(e) 
    if departement: 
     b = Departement.group(1).strip() 
     b=b + "," 
     out_file.write(b) 
    if account: 
     c = account.group(1).strip() 
     c=c +"|" 
     out_file.write(c) 
     if access: 
      d = access.group(1).strip() 
      d=d + "\\n" 
      out_file.write(d) 


file.close() 
out_file.close() 
+0

您是否也包含正则表达式搜索值? “部门”也没有定义。数据文件中也有很多拼写错误。他们应该在那里吗? –

+0

我用随机的例子改变了我的实际数据,所以可能有一些错字..我没有搜索这个例子的正则表达式。但我的数据验证匹配的正则表达式 – lkv

回答

0

使用string formatting来构建你打算写行简化您的过程:

s = '{},{}|{}\n{}|{}' 

的数据分配给变量名

if user_name: 
    user_name = user_name.group(1).strip() 
if Departement: 
    Departement = Departement.group(1).strip() 
if account: 
    account = account.group(1).strip() 
if access: 
    access = access.group(1).strip() 

使用与格式字符串

out_file.write(s.format(Departement, user_name, 
          access1, user_name, 
          access2) 

似乎变量名你有两个access的 - 这是不明确的,从你的帖子,你怎么解压他们......我会让你处理这件事。

+0

谢谢wwii ...它的工作.. – lkv