python正则去除所有html标签只保留内容写入到csv
时间: 2023-09-22 08:15:24 浏览: 141
可以使用Python中的re模块和csv模块来实现这个功能。
首先,我们需要读取HTML文件并使用正则表达式删除所有HTML标签。然后,我们将清理后的文本写入CSV文件中。
下面是一个示例代码:
```python
import re
import csv
# 读取HTML文件
with open('example.html', 'r', encoding='utf-8') as f:
html_text = f.read()
# 删除HTML标签
clean_text = re.sub('<.*?>', '', html_text)
# 将清理后的文本写入CSV文件中
with open('example.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Content'])
writer.writerow([clean_text])
```
在这个例子中,我们首先使用`open()`函数打开HTML文件并使用`read()`方法读取其内容。然后,我们使用`re.sub()`函数和正则表达式`'<.*?>'`删除所有HTML标签。
最后,我们使用`csv.writer()`函数将清理后的文本写入CSV文件中,其中`writerow()`函数用于写入一行数据,`newline=''`参数用于避免在Windows系统上出现多余的空行。
相关问题
写出python代码 1.读取log,当读取到最后一次出现"My name is kitty"时,从下一行开始读 2.删除所有重复的行,只留第一行 3.第一行按照正则规则1分列后,写入新的CSV文件Output 4.从下一行开始按照正则规则2分列后,继续写入新的CSV文件Output
以下是可以实现上述要求的Python代码:
```python
import re
# 正则规则1和规则2
regex1 = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}), (\w+), (\w+), (\d+), (\w+)"
regex2 = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}), (.*)"
# 读取log文件
with open("log.txt", "r") as f:
lines = f.readlines()
# 找到最后一次"My name is kitty"出现的位置
last_kitty_index = -1
for i, line in enumerate(lines):
if "My name is kitty" in line:
last_kitty_index = i
# 从下一行开始读取
new_lines = lines[last_kitty_index+1:]
# 删除重复的行,只留第一行
unique_lines = list(set(new_lines))
output_lines = []
# 第一行按照正则规则1分列后,写入新的CSV文件Output
for line in unique_lines:
if re.match(regex1, line):
match = re.findall(regex1, line)[0]
output_line = ",".join(match) + "\n"
output_lines.append(output_line)
# 从下一行开始按照正则规则2分列后,继续写入新的CSV文件Output
for line in unique_lines:
if re.match(regex2, line):
match = re.findall(regex2, line)[0]
output_line = ",".join(match) + "\n"
output_lines.append(output_line)
# 将结果写入Output文件
with open("Output.csv", "w") as f:
f.writelines(output_lines)
```
python词频统计结果写入csv,Python中CSV列的词频
可以使用Python中的`csv`和`collections`库来实现词频统计并将结果写入CSV文件。
首先,需要读取文本文件并将其转换为单词列表。可以使用正则表达式和字符串方法来实现:
```python
import re
with open('file.txt', 'r') as f:
words = re.findall(r'\b\w+\b', f.read().lower())
```
接下来,使用`collections`库中的`Counter`类来计算每个单词的出现次数:
```python
from collections import Counter
word_counts = Counter(words)
```
然后,将结果写入CSV文件。可以使用`csv`库中的`writerow`方法来逐行写入数据:
```python
import csv
with open('word_counts.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Word', 'Count'])
for word, count in word_counts.items():
writer.writerow([word, count])
```
最后,将上述代码整合成一个完整的程序:
```python
import re
from collections import Counter
import csv
with open('file.txt', 'r') as f:
words = re.findall(r'\b\w+\b', f.read().lower())
word_counts = Counter(words)
with open('word_counts.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Word', 'Count'])
for word, count in word_counts.items():
writer.writerow([word, count])
```
以上代码将每个单词及其出现次数写入CSV文件中的两列。
阅读全文
相关推荐







