【问题标题】:AttributeError: 'filter' object has no attribute 'replace' in Python 3AttributeError:“过滤器”对象在 Python 3 中没有属性“替换”
【发布时间】:2016-10-14 15:28:57
【问题描述】:

我在使用 python 3.x 时遇到了一些问题。在 python 2.x 中。我可以在filter obj 中使用replace attr,但现在我不能使用它。这是我的代码的一部分:

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'

我该如何解决?

【问题讨论】:

  • 加上你的代码充满了xrange...
  • 我不运行这个,我在 python 2 中运行 "filter(str.isupper, s.upper()).replace(from_, to)" 并且效果很好。但是在 python 3 中呢? @vaultah
  • 我解决了 xrange 问题。正如我所说,这是我的代码的一部分。 @Jean-FrançoisFabre
  • replace 是字符串方法。函数过滤器返回一个生成器而不是一个字符串

标签: python python-2.7 python-3.x replace filter


【解决方案1】:

在 python 2 中,filter 如果一个字符串作为输入传递,则返回一个字符串。

过滤器(...) filter(function or None, sequence) -> 列表、元组或字符串

返回那些 function(item) 为真的序列项。如果 函数为无,返回为真的项目。如果序列是一个>元组 或字符串,返回相同类型,否则返回列表。

要在 python 3 中模拟这种行为,只需这样做

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

将iterable转换为字符串,然后你可以执行替换

【讨论】:

    【解决方案2】:

    我认为你可以使用列表推导:

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

    这是你想要的吗?那里有很多代码,所以我可能会遗漏一些东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多