2016-10-14 9 views
1

python 3.xにいくつかの問題があります。 Python 2.xでは。 filter objにreplace attrを使用できましたが、今は使用できません。AttributeError: 'filter'オブジェクトにはPython 3の '​​replace'属性がありません

def uniq(seq): 
    seen = {} 
    return [seen.setdefault(x, x) for x in seq if x not in seen] 

def partition(seq, n): 
    return [seq[i : i + n] for i in xrange(0, len(seq), n)] 

def PlayFairCipher(key, from_ = 'J', to = None): 
    if to is None: 
     to = 'I' if from_ == 'J' else '' 

    def canonicalize(s): 
     return list(filter(str.isupper, s.upper()).replace(from_, to)) 

    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) 

    enc = {} 

    for row in m: 
     for i, j in product(xrange(5), repeat=2): 
      if i != j: 
       enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] 

    for c in zip(*m): 
     for i, j in product(xrange(5), repeat=2): 
      if i != j: 
       enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] 

    for i1, j1, i2, j2 in product(xrange(5), repeat=4): 
     if i1 != i2 and j1 != j2: 
      enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] 

    def sub_enc(txt): 
     lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) 
     return ''.join(enc[a + (b if b else 'X')] for a, b in lst) 

    return sub_enc 

しかし、これはコンパイル時に、私はこれを受け取る:ここに私のコードのセクションはある

、私はそれを修正するにはどうすればよい
AttributeError: 'filter' object has no attribute 'replace' 

+0

プラスあなたのコードを実行できるのpython 3でこの動作をシミュレートするため

filter(...) filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a >tuple or string, return the same type, else return a list.

は 'xrange'がいっぱいです。.. –

+0

私はこれを実行しません、私は "フィルタ(str.isupper、s.upper())を実行します。(from_、to)"をpython 2で置き換えて、これはうまくいきます。 Python 3ではどうですか? @vaultah –

+0

私はxrange問題を解決しました。私が言ったように、これは私のコードのセクションです。 @ Jean-FrançoisFabre –

答えて

2

python 2で、filterは文字列が入力として渡された場合に文字列を返します。文字列に反復可能に変換するために

"".join(filter(str.isupper, s.upper())) 

を行うだけで、その後、あなたが代わる

1

私はあなたがリストの内包表記を使用することができると思う:

[c.replace(from_, to) for c in s.upper() if c.isupper()] 

は何をしたい、このですか?そこにはたくさんのコードがありますので、何かが足りないかもしれません

関連する問題