How to remove duplicate words from text

Discussion in 'Javascript' started by Voetleuce en fênsievry, Jul 22, 2003.

  1. 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."

    Can you direct me to a script (or write one, please) that will remove
    the excess names and leave just one instance of each name, like:

    "Aberdeen Edinburg Inverness etc."

    Thanks in advance!
    [E-mail answers appreciated, but I'll also check the newsgroup.]
    Voetleuce en fênsievry, Jul 22, 2003
    #1
    1. Advertising

  2. "Voetleuce en fênsievry" <> wrote in message
    news:...
    > 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."
    >
    > Can you direct me to a script (or write one, please) that will remove
    > the excess names and leave just one instance of each name, like:
    >
    > "Aberdeen Edinburg Inverness etc."


    You need to be clearer about the nature of your list. How does a
    space-separated list of city/town names cope with 'Chipping Sudbury' or
    'Milton Kenes'. Having decided how the list is going to distinguish one
    distinct place name from the next (comma separated?) you could use the
    String.split method to produce an array of strings - var placeNameArray
    = listText.split( [ delimiter string or regular expression] ); - and
    then create a new Object and assign a new (maybe boolean true) property
    to the Object using each place name from the array as the property name.
    Duplicates would only server to re-set an existing property. Then a -
    for(var propName in Obj) loop would enumerate the created properties of
    the object and could be used to create a duplicate-free list.

    Richard.
    Richard Cornford, Jul 22, 2003
    #2
    1. Advertising

  3. (Voetleuce en fênsievry) writes:

    > 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."


    So your list is a string, and not, e.g., an array.
    We need to be able to delimiter the names, so for now I'll assume that
    spaces delimiter town names.


    > Can you direct me to a script (or write one, please) that will remove
    > the excess names and leave just one instance of each name, like:
    >
    > "Aberdeen Edinburg Inverness etc."


    ---
    function uniqueTowns(towns){
    var arrTowns = towns.split(" ");
    var arrNewTowns = [];
    var seenTowns = {};
    for(var i=0;i<arrTowns.length;i++) {
    if (!seenTowns[arrTowns]) {
    seenTowns[arrTowns]=true;
    arrNewTowns.push(arrTowns);
    }
    }
    return arrNewTowns.join(" ");
    }
    ---
    This function splits the argument string "towns" into an array
    of strings, then runs through them and adds the string to a new
    array the first time it is encountered. This new array is then
    joined to a string again and returned.

    > [E-mail answers appreciated, but I'll also check the newsgroup.]


    Good choice :)
    /L
    --
    Lasse Reichstein Nielsen -
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jul 22, 2003
    #3
  4. JRS: In article <>, seen in
    news:comp.lang.javascript, Lasse Reichstein Nielsen <>
    posted at Tue, 22 Jul 2003 16:05:39 :-

    >function uniqueTowns(towns){
    > var arrTowns = towns.split(" ");
    > var arrNewTowns = [];
    > var seenTowns = {};
    > for(var i=0;i<arrTowns.length;i++) {
    > if (!seenTowns[arrTowns]) {
    > seenTowns[arrTowns]=true;
    > arrNewTowns.push(arrTowns);
    > }
    > }
    > return arrNewTowns.join(" ");
    >}


    That failed in MSIE 4 - no .push().

    The following is simpler, and assumes a sorted list as per example :

    T = "Aberdeen Aberdeen Aberdeen Edinburg Edinburg Inverness etc."

    function uniqueTowns(towns){
    var arrTowns = towns.split(/\s+/), ans = "", Had = ""
    for (var i=0 ; i < arrTowns.length ; i++)
    if ( Had != (Had=arrTowns) ) ans += Had + " "
    return ans }

    uniqueTowns(T)

    However : it's Edinburgh - and what about Store Heddinge, St. Ives, Cape
    Town, & New York?

    --
    © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
    <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
    <URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
    <URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
    Dr John Stockton, Jul 22, 2003
    #4
  5. Dr John Stockton <> writes:

    > That failed in MSIE 4 - no .push().


    And in IE/Mac IIRC. So, add it:
    ---
    if (!Array.prototype.push) {
    Array.prototype.push = function(elem) {
    this[this.length]=elem;
    }
    }
    ---

    > The following is simpler, and assumes a sorted list as per example :
    >
    > T = "Aberdeen Aberdeen Aberdeen Edinburg Edinburg Inverness etc."
    >
    > function uniqueTowns(towns){
    > var arrTowns = towns.split(/\s+/), ans = "", Had = ""
    > for (var i=0 ; i < arrTowns.length ; i++)


    > if ( Had != (Had=arrTowns) )


    You depend on the evaluation of the arguments to "!=" to be
    left-to-right. I know the specification requires it, but it would be
    an easy place for an implementation to break unnoticed, so I would be
    weary using it. It's hard to read as well.

    > ans += Had + " "
    > return ans }
    >
    > uniqueTowns(T)


    > However : it's Edinburgh - and what about Store Heddinge, St. Ives, Cape
    > Town, & New York?


    My version would work for "New York", as long as "York" didn't come
    first :)
    It is unsolvable if there is no clear delimiter between towns. I.e.,
    if both "York" and "New York" are legal names, and the names are space
    separated as well, any solution is bound to break.

    /L
    --
    Lasse Reichstein Nielsen -
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jul 23, 2003
    #5
  6. Dr John Stockton <> wrote in message news:<thWn0zGsxZH$>...

    > However : it's Edinburgh - and what about Store Heddinge,
    > St. Ives, Cape Town, & New York?


    Thanks for everyone's answers -- I'll definitely give it a try.

    To John Stockton and Richard Cornford, sorry, I should have given more
    details (I didn't want to clutter the post with irrelevant details).
    I have a postal code list in XLS format in four colums, the fourth of
    which contains town names. I extracted the town names to plaintext,
    replaced all the spaces with underscores (eg New_York, Cape_Town),
    removed all the fullstops and other non-alphabetic characters (eg
    St_Yves, St_George_s_Mall) and sorted it alphabetically using a word
    processor. Now I'm stuck with a list of names with hundreds of
    duplicates (many of these towns have several postal codes, you see).

    I'm a translator (EN-AF-EN) and I'd like to use the list as a spelling
    reference (chances are that the Post Office will know the correct
    spelling of a place name).

    I see many applications which are useful to translators which can
    easily be solved using JavaScript (and JavaScript is handy too because
    it works offline and on most browsers, and even the ones that are
    browser specific are specific to commonly available browsers). I have
    seen a handy word-count facility, for example. I have also seen a
    spell checker (which doesn't work in Opera and which chokes the
    computer when trying to use more than 100 k words, heh-heh).
    Something to sort words in alphabetical order would be equally useful.

    Some might say "but don't MS Word or Trados or Wordfast have all these
    features?" -- yes but not all translators have access to a computer
    with MS Word installed on it al the time, and most of these JavaScript
    scripts would fit on a stiffy for handy use. Plus, I'm sure there are
    other functions not currently supported by MS Word which can easily be
    accomplished using JavaScript (jargon extraction, for example).

    Thanks again for your replies. I don't know JavaScript myself and I
    often regret it (they say it's easy, but I find it hard).
    Voetleuce en fênsievry, Jul 23, 2003
    #6
  7. Voetleuce en fênsievry

    Mark Szlazak Guest

    Now for a change in pace, see if this or a similar regex solution will
    fit your needs.

    inText = 'Aberdeen Aberdeen Aberdeen Edinburg Edinburg Inverness
    etc.';
    rxDoubled = /\b(\w+)(?:(\s+)\1\b)+/g
    outText = inText.replace(rxDoubled,'$1$2');

    If the non-capture group (?: is not supported, change the regex and
    ordinals to:

    rxDoubled = /\b(\w+)((\s+)\1\b)+/g
    outText = inText.replace(rxDoubled,'$1$3');

    Also, if you need other non-word-character stuff in between like a tag
    then replace (\s+) with ((?:\s|<[^>]+>)+)





    *** Sent via Developersdex http://www.developersdex.com ***
    Don't just participate in USENET...get rewarded for it!
    Mark Szlazak, Jul 23, 2003
    #7
  8. "Voetleuce en fênsievry" <> wrote in message
    news:...
    <snip>
    >Thanks for everyone's answers -- I'll definitely give it a try.

    <snip>

    This is an example using some of the methods suggested. I did make one
    or two changes; lasse's split call used a space character, I changed
    that to a regular expression, Dr John Stockton's function requires
    sorted input so I added a call to the array sort method (if the input is
    pre-sorted then this is not needed and can be removed). On the subject
    of sorting, Dr John Stockton's function always produces sorted output,
    Lasse's will produce sorted output if the input is sorted but a call to
    the array sort method could be added (either just before the final join
    or following the split). My - for(var prop in seenTowns) - method cannot
    guarantee the order of the output.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <script type="text/javascript">

    function uniqueTownsLRN(frm){
    var towns = frm.elements['inputText'].value;
    var arrTowns = towns.split(/\s+/);
    var arrNewTowns = [];
    var seenTowns = {};
    for(var i=0;i<arrTowns.length;i++) {
    if (!seenTowns[arrTowns]) {
    seenTowns[arrTowns]=true;
    arrNewTowns.push(arrTowns);
    }
    }
    frm.elements['outputText'].value = arrNewTowns.join(" ");
    }

    function uniqueTownsDJS(frm){
    var towns = frm.elements['inputText'].value;
    var arrTowns = towns.split(/\s+/).sort(), ans = "", Had = "";
    for(var i=0;i < arrTowns.length;i++)
    if( Had != (Had=arrTowns) )ans += Had + " ";
    frm.elements['outputText'].value = ans;
    }

    function uniqueTownsRC(frm){
    var towns = frm.elements['inputText'].value;
    var st = '', seenTowns = {}, arrTowns = towns.split(/\s+/);
    for(var c = arrTowns.length;c--;){
    seenTowns[arrTowns[c]] = true;
    }
    for(var prop in seenTowns){
    st += prop+' ';
    }
    frm.elements['outputText'].value = st;
    }

    </script>

    </head>
    <body>
    <form name="testForm" action="" method="get"
    onsubmit="return subTests()">
    <textarea name="inputText" cols="70" rows="8">St_Yves St_George_s_Mall
    Aberdeen Aberdeen New_York Cape_Town Aberdeen Edinburgh
    Edinburgh Inverness St_Yves St_George_s_Mall New_York
    Aberdeen Aberdeen New_York Cape_Town Aberdeen Edinburgh
    Edinburgh Inverness St_Yves St_George_s_Mall New_York
    Cape_Town New_York Cape_Town</textarea><br>
    <input type="button" value="Lasse Reichstein Nielsen Version"
    onclick="uniqueTownsLRN(this.form);"><br>
    <input type="button" value="Dr John Stockton Version"
    onclick="uniqueTownsDJS(this.form);"><br>
    <input type="button" value="Richard Cornford Version"
    onclick="uniqueTownsRC(this.form);"><br>
    <textarea name="outputText" cols="70" rows="8"></textarea>
    </form>
    </body>
    </html>

    Richard.
    Richard Cornford, Aug 2, 2003
    #8
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Strøiman
    Replies:
    1
    Views:
    2,064
    Peter Strøiman
    Aug 23, 2005
  2. Richard Heathfield
    Replies:
    7
    Views:
    348
    Barry Schwarz
    Oct 5, 2003
  3. Replies:
    11
    Views:
    641
    Neil Cerutti
    Nov 3, 2005
  4. utab

    Words Words

    utab, Feb 16, 2006, in forum: C++
    Replies:
    6
    Views:
    412
    Daniel T.
    Feb 16, 2006
  5. BerlinBrown
    Replies:
    6
    Views:
    4,416
Loading...

Share This Page