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

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

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(&quot;build files&quot;, &quot;adlist.txt&quot;), encoding=&quot;utf8&quot;))

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(&quot;Blocking url --- &quot;+url.toString())
		return False
	else: 
		print(&quot;TYPE&quot;, _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(&quot;build files&quot;, &quot;adlist.txt&quot;), encoding=&quot;utf8&quot;))
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&gt;=0

    filter_ed = filter(positive, array) # return [1, 2, 3, 4, 54]


</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:

确定