Python现有一文本文件/webpage.txt,是从某网站保存下来的html源文件,文件编码为gb18030 编写程序,打开并读取该文件内容,将其中所有中文连接成一个字符串输出。 提示:中文标准暂定为 ASCII 码值超过128且排除以下字符 :,!…?!“”、《》 重要提示:打开的文件必须关闭!!!
时间: 2024-02-23 21:59:24 浏览: 81
好的,我来写一个Python程序来实现这个功能:
```python
import re
filename = 'webpage.txt'
with open(filename, 'r', encoding='gb18030') as file:
content = file.read()
chinese = re.findall('[\u4e00-\u9fa5]+', content)
# 过滤掉标点符号
chinese = [c for c in chinese if c not in ',!…?!“”、《》']
result = ''.join(chinese)
print(result)
```
这段程序首先打开指定的文件,读取其中的内容。然后使用正则表达式 `[\u4e00-\u9fa5]+` 匹配所有的中文,并将其保存到列表 `chinese` 中。接着,我们过滤掉标点符号,然后将所有中文连接成一个字符串 `result` 并输出。最后记得关闭文件。
相关问题
使用Python并不使用import,完成该题:现有一文本文件/webpage.txt,是从某网站保存下来的html源文件,文件编码为gb18030 编写程序,打开并读取该文件内容,将其中所有中文连接成一个字符串输出。 提示:中文标准暂定为 ASCII 码值超过128且排除以下字符 :,!…?!“”、《》 重要提示:打开的文件必须关闭!!!
好的,以下是代码实现:
```python
with open('webpage.txt', 'r', encoding='gb18030') as f:
chinese_str = ''
for line in f:
for word in line:
if 128 < ord(word) < 256 and word not in ',!…?!“”、《》':
chinese_str += word
print(chinese_str)
```
这个程序会打开名为 'webpage.txt' 的文件,并按行读取其中的内容。然后,它会遍历每个字符,如果这个字符是中文,则将其添加到一个字符串 `chinese_str` 中。
需要注意的是,为了确保程序能够正确地处理中文字符,我们使用了 `encoding='gb18030'` 来指定文件编码。此外,我们还使用了 `with open()` 语句来打开文件,并在处理完文件后自动关闭它,这是一种良好的编程习惯。
python爬取https://www.yjbys.com/mingyan/mingren/1691125.html网页中的名人名言的代码
要使用Python爬取网页中的名人名言,我们可以使用`requests`库来发送HTTP请求,使用`BeautifulSoup`库来解析HTML内容。以下是一个示例代码,演示如何从指定网页中提取名人名言:
```python
import requests
from bs4 import BeautifulSoup
# 目标网页URL
url = 'https://www.yjbys.com/mingyan/mingren/1691125.html'
# 发送HTTP请求并获取响应
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到包含名人名言的标签
quotes = soup.find_all('div', class_='neirong')
# 提取并打印名人名言
for quote in quotes:
print(quote.get_text(strip=True))
else:
print(f"Failed to retrieve the webpage. Status code: {response.status_code}")
```
在这个示例中,我们首先导入了`requests`和`BeautifulSoup`库。然后,我们定义了目标网页的URL,并使用`requests.get`方法发送HTTP请求。
如果请求成功(即状态码为200),我们使用`BeautifulSoup`解析网页内容。接着,我们使用`find_all`方法找到所有包含名人名言的`<div>`标签,并提取其中的文本内容。
阅读全文
相关推荐















