python对行去重代码
时间: 2023-10-16 07:06:00 浏览: 38
你可以使用Python的集合(set)来对行去重。下面是一个示例代码:
```python
def remove_duplicate_lines(file_path):
lines = set()
with open(file_path, 'r') as file:
for line in file:
# 移除行末尾的换行符
line = line.rstrip('\n')
if line not in lines:
lines.add(line)
# 将去重后的内容写回文件
with open(file_path, 'w') as file:
file.write('\n'.join(lines))
```
你可以调用`remove_duplicate_lines`函数,并传递文件路径作为参数,该函数将会从文件中去除重复的行。请确保提供的文件路径是正确的。
相关问题
python爬虫数据去重代码
以下是Python爬虫数据去重的代码示例:
```python
import hashlib
# 定义一个去重类
class Deduplication(object):
def __init__(self):
self.hash = set()
# 判断url是否重复
def is_duplicate(self, url):
fp = hashlib.sha1()
fp.update(url.encode('utf-8'))
url_sha1 = fp.hexdigest()
if url_sha1 in self.hash:
return True
else:
self.hash.add(url_sha1)
return False
```
使用示例:
```python
# 创建一个去重对象
dedup = Deduplication()
# 判断url是否重复
if dedup.is_duplicate(url):
print('该url已经被爬取过了')
else:
# 爬取该url
...
```
python列表元素去重代码
以下是Python列表元素去重的代码示例:
方法一:使用set()
```
my_list = [1, 2, 2, 3, 3, 4, 5, 5, 6]
my_list = list(set(my_list))
print(my_list)
```
方法二:使用循环
```
my_list = [1, 2, 2, 3, 3, 4, 5, 5, 6]
new_list = []
for i in my_list:
if i not in new_list:
new_list.append(i)
print(new_list)
```
方法三:使用列表推导式
```
my_list = [1, 2, 2, 3, 3, 4, 5, 5, 6]
new_list = list(set([i for i in my_list]))
print(new_list)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)