如何修复:TypeError: filter期望2个参数,但只提供了1个

huangapple go评论213阅读模式
英文:

How to fix: TypeError: filter expected 2 arguments, got 1

问题

  1. 使用PythonPyQt5/PySide6制作浏览器。我实现了一个广告拦截器,它使用列表来阻止广告以选项卡的方式打开。
  2. ```python
  3. class WebPage(QWebEnginePage):
  4. adblocker = filter(open(os.path.join("build files", "adlist.txt"), encoding="utf8"))
  5. def __init__(self, parent=None):
  6. super().__init__(parent)
  7. def acceptNavigationRequest(self, url, _type, isMainFrame):
  8. urlString = url.toString()
  9. resp = False
  10. resp = WebPage.adblocker.match(url.toString())
  11. if resp:
  12. print("阻止URL --- " + url.toString())
  13. return False
  14. else:
  15. print("类型", _type)
  16. return True
  17. return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)

我尝试修复这个问题,但没有成功。

我期望代码不会引发错误。该代码应该防止用户打开广告。

  1. <details>
  2. <summary>英文:</summary>
  3. I am making a browser using python and PyQt5/PySide6. I implemented an adblock which uses a list to block ads from opening as tabs.
  4. `

class WebPage(QWebEnginePage):

  1. adblocker = filter(open(os.path.join(&quot;build files&quot;, &quot;adlist.txt&quot;), encoding=&quot;utf8&quot;))
  2. def __init__(self, parent=None):
  3. super().__init__(parent)
  4. def acceptNavigationRequest(self, url, _type, isMainFrame):
  5. urlString = url.toString()
  6. resp = False
  7. resp = WebPage.adblocker.match(url.toString())
  8. if resp:
  9. print(&quot;Blocking url --- &quot;+url.toString())
  10. return False
  11. else:
  12. print(&quot;TYPE&quot;, _type)
  13. return True
  14. return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)
  1. I tried to fix this, but to no avail.
  2. I am expecting the code to raise no errors. The code is supposed to prevent the user from opening ads.
  3. </details>
  4. # 答案1
  5. **得分**: 0
  6. 你需要将筛选功能添加到filter()函数中:
  7. ```python
  8. adblocker = filter(filter_by, open(os.path.join("build files", "adlist.txt"), encoding="utf8"))
  9. ```
  10. 其中,filter_by是一个接受数组中的元素并返回布尔值的函数。示例:
  11. ```python
  12. array = [1, 2, 3, 4, 54, -5, -1]
  13. def positive(x):
  14. return x >= 0
  15. filter_ed = filter(positive, array) # 返回 [1, 2, 3, 4, 54]
  16. ```
  17. <details>
  18. <summary>英文:</summary>
  19. you need to add the filtering function to filter()
  20. adblocker = filter(filter_by, open(os.path.join(&quot;build files&quot;, &quot;adlist.txt&quot;), encoding=&quot;utf8&quot;))
  21. where filter_by is a function that takes an element of the giving array and returns a bool
  22. example:
  23. array = [1, 2, 3, 4, 54, -5, -1]
  24. def positive(x):
  25. return x&gt;=0
  26. filter_ed = filter(positive, array) # return [1, 2, 3, 4, 54]
  27. </details>

huangapple
  • 本文由 发表于 2023年4月7日 03:48:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定