2016-09-24 2 views
0
  1. 私の入力ファイル:クローンリストを一度印刷し、Pythonで辞書にロードするには?

    cs 124456 powerful 
    cs 124456 powerful 
    me  125454 easy 
    me 125455 easy 
    me 125455 easy 
    ec 125555 done 
    ec 127678 fine 
    ec 127678 fine 
    ci 127678 fine 
    ci 127678 fine 
    eee 125678 good 
    eee 125678 good 
    eee 125678 good 
    eee 125678 bad` 
    
  2. 予想される出力:

    no.name reg perform 
    1.cs 124456 powerful 
    2.me 125454 easy 
    3.me 125455 easy 
    4.ec 125555 done 
    5.ec 127678 fine 
    6.ci 127678 fine 
    7.eee 125678 good 
    8.eee 125678 bad 
    
  3. 私のコード:

    import os 
    os.chdir("d:/filer") 
    import re   
    def first(line): 
        f=re.findall("[a-z]+",line,flags=0) 
        return f 
    def num(line): 
        n=re.findall("\d{6}",line,flags=0) 
        return n 
    with open("once.txt","r") as sa: 
        for line in sa.readlines(): 
          home=first(line) 
          number=num(line) 
          x=home[0] 
          y=number[0] 
          z=home[1] 
          if x!=0 and y!=0 and z!=0:  
          print [x,y,z] 
    
  4. 私は、ファイルを開いて、それらを一行ずつ読み込みます。次に、それらの数字とテキストを正規表現を使用して抽出し、インデックスでリストに格納しました。今私はユニークでクローンされていないリストだけを求めます。その後、それらを辞書にロードします。誰かが私を助けることができますか?

答えて

0

クローニングを防止するために、あなたはそうのようなset()を使用することがあります。

results = set() # Construct a set 
with open("once.txt","r") as sa: 
    for line in sa.readlines(): 
      home=first(line) 
      number=num(line) 
      x=home[0] 
      y=number[0] 
      z=home[1] 
      if x!=0 and y!=0 and z!=0: 
      if (x,y,z) not in results: # Check if the set already contains the result 
       results.add((x,y,z)) # If it doesn't, add to the set and print. 
       print [x,y,z] 

また、私は少しあなたのコードを整理示唆しています。次のようにわかりやすくするために1正規表現を作成することができます:

results = set() # Construct a set 
with open("once.txt","r") as sa: 
    count = 0 
    for line in sa: # No need for readlines() 
     match = re.match(r"(\w+)\s+(\d+)\s+(\w+)") 

     if match is None: 
      continue 

     result = match.groups() 
     if result not in results: # Check if the set already contains the result 
      count += 1 
      results.add(result) # If it doesn't, add to the set and print. 
      print count, result 
関連する問題