473,577 Members | 3,213 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to remove duplicate words from text

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.]
Jul 20 '05 #1
7 23910
"Voetleuce en fênsievry" <ca******@websu rfer.co.za> wrote in message
news:f0******** *************** ***@posting.goo gle.com...
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.
Jul 20 '05 #2
ca******@websur fer.co.za (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(tow ns){
var arrTowns = towns.split(" ");
var arrNewTowns = [];
var seenTowns = {};
for(var i=0;i<arrTowns. length;i++) {
if (!seenTowns[arrTowns[i]]) {
seenTowns[arrTowns[i]]=true;
arrNewTowns.pus h(arrTowns[i]);
}
}
return arrNewTowns.joi n(" ");
}
---
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 - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #3
JRS: In article <k7**********@h otpop.com>, seen in
news:comp.lang. javascript, Lasse Reichstein Nielsen <lr*@hotpop.com >
posted at Tue, 22 Jul 2003 16:05:39 :-
function uniqueTowns(tow ns){
var arrTowns = towns.split(" ");
var arrNewTowns = [];
var seenTowns = {};
for(var i=0;i<arrTowns. length;i++) {
if (!seenTowns[arrTowns[i]]) {
seenTowns[arrTowns[i]]=true;
arrNewTowns.pus h(arrTowns[i]);
}
}
return arrNewTowns.joi n(" ");
}


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(tow ns){
var arrTowns = towns.split(/\s+/), ans = "", Had = ""
for (var i=0 ; i < arrTowns.length ; i++)
if ( Had != (Had=arrTowns[i]) ) 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.demo n.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #4
Dr John Stockton <sp**@merlyn.de mon.co.uk> writes:
That failed in MSIE 4 - no .push().
And in IE/Mac IIRC. So, add it:
---
if (!Array.prototy pe.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(tow ns){
var arrTowns = towns.split(/\s+/), ans = "", Had = ""
for (var i=0 ; i < arrTowns.length ; i++) if ( Had != (Had=arrTowns[i]) )
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 - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #5
Dr John Stockton <sp**@merlyn.de mon.co.uk> wrote in message news:<th******* *******@merlyn. demon.co.uk>...
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_Mal l) 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).
Jul 20 '05 #6
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!
Jul 20 '05 #7
"Voetleuce en fênsievry" <ca******@websu rfer.co.za> wrote in message
news:f0******** *************** ***@posting.goo gle.com...
<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[i]]) {
seenTowns[arrTowns[i]]=true;
arrNewTowns.pus h(arrTowns[i]);
}
}
frm.elements['outputText'].value = arrNewTowns.joi n(" ");
}

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[i]) )ans += Had + " ";
frm.elements['outputText'].value = ans;
}

function uniqueTownsRC(f rm){
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="retur n subTests()">
<textarea name="inputText " cols="70" rows="8">St_Yve s St_George_s_Mal l
Aberdeen Aberdeen New_York Cape_Town Aberdeen Edinburgh
Edinburgh Inverness St_Yves St_George_s_Mal l New_York
Aberdeen Aberdeen New_York Cape_Town Aberdeen Edinburgh
Edinburgh Inverness St_Yves St_George_s_Mal l New_York
Cape_Town New_York Cape_Town</textarea><br>
<input type="button" value="Lasse Reichstein Nielsen Version"
onclick="unique TownsLRN(this.f orm);"><br>
<input type="button" value="Dr John Stockton Version"
onclick="unique TownsDJS(this.f orm);"><br>
<input type="button" value="Richard Cornford Version"
onclick="unique TownsRC(this.fo rm);"><br>
<textarea name="outputTex t" cols="70" rows="8"></textarea>
</form>
</body>
</html>

Richard.
Jul 20 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3064
by: Tony Johansson | last post by:
Hello! I have some problem with STL function remove I have two classes called Handle which is a template class and Integer which is not a template class. The Integer class is just a wrapper class for a primitive int with some methods. I don't show the Integer class because it will not add any information to my problem. Main is using some...
8
4185
by: Joseph | last post by:
I have a textBox that people writes stories in it. They can use for format. I have Aspell installed on the server, so people can make correction to their text. Sometimes, they forget to add a space after a period. So Aspell reads the last word of a sentence and the first word of the next sentence as a single world, which gives an error,...
18
23433
by: prasanna.hariharan | last post by:
Hi guys, I want to remove certain words from a c++ string. The list of words are in a file with each word in a new line. I tried using the std::transform, but it dint work. Anybody got a clue as to how i should go about this. thanks a lot, Hp
11
7903
by: tmshaw | last post by:
I'm a newb in a c++ class... I need to read the standard input into a couple strings. Then determine whether or not the same word is used IN SUCCESSION (ex. this cat cat is really mean.). Then count and print the word and how many times it was used. So using the above example, it would print out the words that were used in succession and...
5
2122
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
5
3634
by: dale.zjc | last post by:
I've got the following table data: 11652 5.99 11652 0.14 12996 5.03 12996 0.12 12996 7.00 And I need to write a query to return only rows 2 and 4, since the remaining rows have duplicate IDs. I've tried the Group By, but am
5
2451
by: kosta.triantafillou | last post by:
Hi all, I have a form that contains a lot of values. On this form there are also alot of popups that can be brought up. One of them does the following: Takes 2 values (x and y), concatenates them together with an underscore in between and adds them to a select box in the same popup (z). Then, when a user clicks a save button located on...
2
2117
by: woocha | last post by:
I read this thread and realized that it was exactly what I was looking for. The problem is I need it to be done with sentences not words. I have a problems with typing the same thought down twice in a large text column of thoughts and ideas. This piece of software that I found on thread thread89492 works really well for words, but not for...
2
2697
by: sejal17 | last post by:
hello I want to check duplicate word in textarea.In textarea,all words are separated by comma.No words are allowed with enter or white space.And the limit is only 7 words i want to insert.I want the code of this.Please help me. Thanks..........
0
7845
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...
0
7776
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...
1
7869
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8143
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...
1
5664
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...
0
5340
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...
0
3779
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...
0
3797
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1385
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.