英文:
How to fix: TypeError: filter expected 2 arguments, got 1
问题
使用Python和PyQt5/PySide6制作浏览器。我实现了一个广告拦截器,它使用列表来阻止广告以选项卡的方式打开。
```python
class WebPage(QWebEnginePage):
adblocker = filter(open(os.path.join("build files", "adlist.txt"), encoding="utf8"))
def __init__(self, parent=None):
super().__init__(parent)
def acceptNavigationRequest(self, url, _type, isMainFrame):
urlString = url.toString()
resp = False
resp = WebPage.adblocker.match(url.toString())
if resp:
print("阻止URL --- " + url.toString())
return False
else:
print("类型", _type)
return True
return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)
我尝试修复这个问题,但没有成功。
我期望代码不会引发错误。该代码应该防止用户打开广告。
<details>
<summary>英文:</summary>
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.
`
class WebPage(QWebEnginePage):
adblocker = filter(open(os.path.join("build files", "adlist.txt"), encoding="utf8"))
def __init__(self, parent=None):
super().__init__(parent)
def acceptNavigationRequest(self, url, _type, isMainFrame):
urlString = url.toString()
resp = False
resp = WebPage.adblocker.match(url.toString())
if resp:
print("Blocking url --- "+url.toString())
return False
else:
print("TYPE", _type)
return True
return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)
I tried to fix this, but to no avail.
I am expecting the code to raise no errors. The code is supposed to prevent the user from opening ads.
</details>
# 答案1
**得分**: 0
你需要将筛选功能添加到filter()函数中:
```python
adblocker = filter(filter_by, open(os.path.join("build files", "adlist.txt"), encoding="utf8"))
```
其中,filter_by是一个接受数组中的元素并返回布尔值的函数。示例:
```python
array = [1, 2, 3, 4, 54, -5, -1]
def positive(x):
return x >= 0
filter_ed = filter(positive, array) # 返回 [1, 2, 3, 4, 54]
```
<details>
<summary>英文:</summary>
you need to add the filtering function to filter()
adblocker = filter(filter_by, open(os.path.join("build files", "adlist.txt"), encoding="utf8"))
where filter_by is a function that takes an element of the giving array and returns a bool
example:
array = [1, 2, 3, 4, 54, -5, -1]
def positive(x):
return x>=0
filter_ed = filter(positive, array) # return [1, 2, 3, 4, 54]
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论