473,626 Members | 3,948 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to remove the duplicate lines retaining first occurences

8 New Member
Let's say a input text file "input_msg. txt" file ( file size is 70,000 kb ) contains following records..

Jan 1 02:32:40 hello welcome to python world
Jan 1 02:32:40 hello welcome to python world
Mar 31 23:31:55 learn python
Mar 31 23:31:55 learn python be smart
Mar 31 23:31:56 python is good scripting language
Jan 1 00:00:01 hello welcome to python world
Jan 1 00:00:02 hello welcome to python world
Mar 31 23:31:55 learn python
Mar 31 23:31:56 python is good scripting language

The expected output file ( Let's say outputfile.txt ) should contain below records...

Jan 1 02:32:40 hello welcome to python world
Jan 1 02:32:40 hello welcome to python world
Mar 31 23:31:55 learn python
Mar 31 23:31:55 learn python be smart
Mar 31 23:31:56 python is good scripting language
Jan 1 00:00:01 hello welcome to python world
Jan 1 00:00:02 hello welcome to python world

Note: I need all the records (including duplicate) which are starting with "Jan 1" and also I don't need Duplicate records not starting with "Jan 1"

I have tried the following program where all the duplicate records are getting deleted.
Expand|Select|Wrap|Line Numbers
  1. def remove_Duplicate_Lines(inputfile, outputfile):  
  2.    with open(inputfile) as fin, open(outputfile, 'w') as out:
  3.       lines = (line.rstrip() for line in fin)
  4.       unique_lines = OrderedDict.fromkeys( (line for line in lines if line) )
  5.       out.writelines("\n".join(unique_lines.iterkeys()))
  6.  return 0
Oputput of my program are below:

Jan 1 02:32:40 hello welcome to python world
Mar 31 23:31:55 learn python
Mar 31 23:31:55 learn python be smart
Mar 31 23:31:56 python is good scripting language
Jan 1 00:00:01 hello welcome to python world

Your help would be appreciated!!!
Jul 15 '15 #1
7 2186
bvdet
2,851 Recognized Expert Moderator Specialist
Use a for loop and conditionally append to a list.
Expand|Select|Wrap|Line Numbers
  1. data = """Jan 1 02:32:40 hello welcome to python world
  2. Jan 1 02:32:40 hello welcome to python world
  3. Mar 31 23:31:55 learn python
  4. Mar 31 23:31:55 learn python be smart
  5. Mar 31 23:31:56 python is good scripting language
  6. Jan 1 00:00:01 hello welcome to python world
  7. Jan 1 00:00:02 hello welcome to python world
  8. Mar 31 23:31:55 learn python
  9. Mar 31 23:31:56 python is good scripting language"""
  10.  
  11. output = []
  12.  
  13. for line in data.split("\n"):
  14.     if line.startswith("Jan 1"):
  15.         output.append(line)
  16.     elif line not in output:
  17.         output.append(line)
  18.  
  19. print "\n".join(output)
The output:
Expand|Select|Wrap|Line Numbers
  1. >>> Jan 1 02:32:40 hello welcome to python world
  2. Jan 1 02:32:40 hello welcome to python world
  3. Mar 31 23:31:55 learn python
  4. Mar 31 23:31:55 learn python be smart
  5. Mar 31 23:31:56 python is good scripting language
  6. Jan 1 00:00:01 hello welcome to python world
  7. Jan 1 00:00:02 hello welcome to python world
  8. >>> 
Jul 15 '15 #2
helloR
8 New Member
@bvdet: Thanks you very much!! I have already been tried this solution but here the problem is if the input message file size is more then it takes more time....

Below is the program which I have tried:
Expand|Select|Wrap|Line Numbers
  1. inputFile = open("in.txt", "r")
  2. log = []
  3. for line in inputFile:
  4.     if line in log and line[0:5] != "Jan 1":
  5.         pass
  6.     else:
  7.         log.append(line)
  8. inputFile.close()
  9. outFile = open("out.txt", "w")
  10. for item in log:
  11.     outFile.write(item)
  12. outFile.close()
  13.  
Note: I have tried with input file size as ~70000 kb and it takes ~9 minutes to complete the execution.

Pls let me know if we can do it some elegant way.....
Jul 15 '15 #3
bvdet
2,851 Recognized Expert Moderator Specialist
Try writing to the file one time.
Expand|Select|Wrap|Line Numbers
  1. outFile.write("\n".join(log))
Jul 15 '15 #4
helloR
8 New Member
@bvet: You mean something like below:
Expand|Select|Wrap|Line Numbers
  1. inputFile = open("in.txt", "r")
  2. outFile = open("out.txt", "w")
  3. log = []
  4. for line in inputFile:
  5.    if line in log and line[0:5] != "Jan 1":
  6.       pass
  7.    else:
  8.       log.append(line)
  9.    outFile.write("\n".join(log))
  10. inputFile.close()
  11. outFile.close()
  12.  
Pls correct me if i am wrong.
Jul 16 '15 #5
bvdet
2,851 Recognized Expert Moderator Specialist
No, write to the file outside of the for loop:
Expand|Select|Wrap|Line Numbers
  1. outFile.write("\n".join(log))
  2. inputFile.close()
  3. outFile.close()
Jul 17 '15 #6
helloR
8 New Member
@bvdet: Thank you for your help!!! This is working but still there is performance issue whenever input file size is more....

Could you please take a look into below code...
Expand|Select|Wrap|Line Numbers
  1. def remove_Duplicate_Lines(inputfile, outputfile):
  2.    with open(inputfile) as fin, open(outputfile, 'w') as out:
  3.       lines = (line.rstrip() for line in fin)
  4.       unique_lines = OrderedDict.fromkeys( (line for line in lines if line) )
  5.       out.writelines("\n".join(unique_lines.iterkeys()))
  6.    return 0
  7.  
Jul 18 '15 #7
bvdet
2,851 Recognized Expert Moderator Specialist
You are iterating over the lines in the file twice. Try eliminating one of them. It is possible OrderedDict may be slower than a for loop. I don't know one way or the other. You can use module timeit to check different methods.
Jul 18 '15 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

7
23915
by: Voetleuce en fênsievry | last post by:
Hello everyone. I'm not a JavaScript author myself, but I'm looking for a method to remove duplicate words from a piece of text. This text would presumably be pasted into a text box. I have, for example, a list of town names, but there are hundreds of duplicates, like: "Aberdeen Aberdeen Aberdeen Edinburg Edinburg Inverness etc."
5
2124
by: RSBakshi | last post by:
Can any body tell me how to find duplicate lines in C i have tried to find using Binary tree and Text files but not suceeded .. It works for Word but not for lines please help me you can write suggetion to my email : rsbakshi@gmail.com
1
5245
by: Allerdyce.John | last post by:
I have a vector of Pair of int: typedef pair<int, int> MyPair; typedef vector <MyPair > MyVector I would like to remove entries if their first are equal, or if their value is swap ( first of first pair equals to seconds of second pair): bool equals(MyPair src, MyPair dest ) { if (( src.first == dest.first) && ( src.second == dest.second))
3
2604
by: dazzle | last post by:
I have an XML file and I would like to remove duplicate nodes within it but I can't get my head round on how to do this. Example XML file: <root> <plugin> <title>A9</title> <url>some url</url>
10
1677
by: umut.tabak | last post by:
Dear all, I am quite new to python. I would like to remove two lines from a file. The file starts with some comments, the comment sign is $. The file structure is $ $ $ $
1
16597
by: JTreefrog | last post by:
Hello - I've read a ton of stuff about deleting duplicate values in an array. They are all very useful - they just haven't addressed an array of objects. Here's my array: var sDat = ; The array is produced from JSON sent to me from a database query. I can't do a "group by" in the sql query - i actually need the repeats in a different array. Anyway - I want to be able to remove duplicate sDat.sid entries in my sDat array - but I'm...
1
1827
by: JRWarring | last post by:
I have a VB application with about 75 installations that uses the Crystal Control (Version 7.0) to print Crystal RPTs. On about 7 of these installations the clients are getting duplicate lines (usually on the last page or a single page report). 1) Using the same data (and reports) we cannot create this problem on any workstations execpt the 7 workstations that have the problem. 2) We do not think it a data problem, since we can clearly see in...
2
1606
by: Hariny | last post by:
Hi, Here is my query: select a.out_tar||'~'|| a.out_csi_id||'~'||a.out_cust_name||'~'||a.out_id||'~'||b.out_id||'~'||a.out_category||'~'|| b.out_category||'~'|| to_char(a.out_start_date, 'fm dd-mon-yyyy hh24:mi') ||'~'|| to_char(a.out_end_date, 'fm dd-mon-yyyy hh24:mi') ||'~'|| to_char(b.out_start_date, 'fmdd-mon-yyyy hh24:mi') ||'~'|| to_char(b.out_end_date, 'fmdd-mon-yyyy hh24:mi')||'~'||c.ots_inst_label from
1
3467
by: tosachinji | last post by:
Hi I am new to xslt. Could you please tell me, how can we remove duplicate records from a xml file. Here is the xml file: <Row> <Cell><Data>Active</Data></Cell> <Cell><Data>D</Data></Cell> <Cell><Data>1</Data></Cell>
0
8266
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8199
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8505
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5574
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4092
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.