如何添加findall属性,如何使read()和findall结合
时间: 2024-05-06 18:19:02 浏览: 9
如果你想要在Python中使用`findall()`方法,你需要导入`re`模块,这个模块提供了正则表达式的支持。然后你可以使用`re.findall()`方法来进行字符串匹配。
举个例子,假设你有一个文本文件`example.txt`,里面包含以下内容:
```
This is an example text file.
It contains some lines of text.
Some of the lines have numbers in them, like 123 or 456.
```
你可以使用以下代码来读取文件并查找包含数字的行:
```python
import re
with open('example.txt', 'r') as f:
for line in f:
if re.findall(r'\d', line):
print(line)
```
在上面的代码中,我们使用了`re.findall()`方法来查找包含数字的行。正则表达式`\d`表示匹配任何数字字符。如果在当前行中找到了数字字符,`re.findall()`方法会返回一个包含这些数字字符的列表,否则返回一个空列表。我们可以使用`if`条件语句来判断是否找到了数字字符,如果找到了就打印这一行。
如果你想将`read()`和`findall()`结合起来使用,可以将读取的文本作为参数传递给`re.findall()`方法,如下所示:
```python
import re
with open('example.txt', 'r') as f:
text = f.read()
lines_with_numbers = re.findall(r'\d', text)
print(lines_with_numbers)
```
在上面的代码中,我们首先使用`f.read()`方法读取整个文件的文本内容,然后将这个文本内容作为参数传递给`re.findall()`方法,查找包含数字的行。`re.findall()`方法会返回一个包含所有数字字符的列表,我们将其存储在`lines_with_numbers`变量中,并打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
注释以下代码from re import findall from urllib.parse import urljoin from urllib.request import urlopen, Request url = r'http://jwc.sdtbu.edu.cn/info/2002/5418.htm' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36', 'Referer': url, } # 不加这一项会有防盗链提示 req = Request(url=url, headers=headers) with urlopen(req) as fp: content = fp.read().decode() pattern = r'(.+?)' for fileUrl, fileName in findall(pattern, content): if 'javascript' in fileUrl: continue fileUrl = urljoin(url, fileUrl) req = Request(url=fileUrl, headers=headers) with urlopen(req) as fp1: with open(fileName, 'wb') as fp2: fp2.write(fp1.read())
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)