python去除文件中重复的行实例

yipeiwu_com6年前Python基础

python去除文件中重复的行,我们可以设置一个一个空list,res_list,用来加入没有出现过的字符行!

如果出现在res_list,我们就认为该行句子已经重复了,可以再加入到记录重复句子的list中。

如下代码:

# -*- coding: UTF-8 -*-
#程序功能是为了完成判断文件中是否有重复句子
#并将重复句子打印出来
 
res_list = []
#f = open('F:/master/master-work/code_of_graduate/LTP_data/raw_plain.txt','r')
f = open('F:/master/master-work/code_of_graduate/chu_li_shuju/ldc-weibo-train-res.txt','r')
res_dup = []
index = 0
file_dul = open('F:/master/master-work/code_of_graduate/chu_li_shuju/ldc-weibo-train-dul.txt', 'w')
for line in f.readlines():
 index = index + 1
 if line in res_list:
  temp_str = ""
  temp_str = temp_str + str(index)     #要变为str才行
  temp_line = ''.join(line)
  temp_str = temp_str+temp_line
  #最终要变为str类型
  file_dul.write(temp_str);       #将重复的存入到文件中
 else:
  res_list.append(line)

以上这篇python去除文件中重复的行实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python二维数组实现求出3*3矩阵对角线元素的和示例

题目:求一个3*3矩阵对角线元素之和。 程序分析:利用双重for循环控制输入二维数组,再将a[i][i]累加后输出。 def two_dimensionalArray(self):...

将python2.7添加进64位系统的注册表方式

解决问题:python2.7无法在注册表中被识别,即在安装NumPy和SciPy等出现“python version 2.7 required, which was not found...

浅谈python的dataframe与series的创建方法

如下所示: # -*- coding: utf-8 -*- import numpy as np import pandas as pd def main(): s = pd.S...

python 数字类型和字符串类型的相互转换实例

一、python中字符串转换成数字 (方法1) 类中进行导入:import string str='555' num=string.atoi(str) num即为str转换成的数字...

python 读入多行数据的实例

python 读入多行数据的实例

一、前言 本文主要使用python 的raw_input() 函数读入多行不定长的数据,输入结束的标志就是不输入数字情况下直接回车,并填充特定的数作为二维矩阵 二、代码 def ge...