I am making a little doc's text searching app using technical stack (react + nodejs + mongodb).
For example if I type "chicken" on my search bar , i will have a whole article about chicken in my result (e.g : The most popular chicken's restaurant closed tonight because of lot of complain about chicken taste, all the employee lost their jobs ) .
The text is often too long to display , what i want to do is get an extract of the word with keyword like : "The most popular chicken's restaurant ... about chicken taste..." .
Do you have any idea about a function than can do that ?
( keyword + max length in parameter). I tried with substring and splice and split but i can't find out the easiest way to do that.
Thanks!
I have given a try to search for the keyword, take two intial words and two words after keyword and joined them with "...".
var longString = "The most popular chicken's restaurant closed tonight because of lot of complain about chicken taste, all the employee lost their jobs";
var keyword = "chicken";
var allWords = longString.split(" ");
var indices = [];
allWords.forEach((word,index)=>{(word.indexOf(keyword)>=0) ? indices.push(index):""});
var newStrings = indices.map((i)=>{
let temp="";
temp=allWords[i-2]?allWords[i-2]+" ":"";
temp+=allWords[i-1]?allWords[i-1]+" ":"";
temp+=allWords[i];
temp+=allWords[i+1]?" "+allWords[i+1]:"";
temp+=allWords[i+2]?" "+allWords[i+2]:"";
return temp;
})
console.log("..."+newStrings.join("...")+"...");
You could use a regular expression that matches your keyword and some words before and after it, e.g. like this:
(?:\w+[\s,;:'".!?]+){0,3}(chicken)(?:[\s,;:'".!?]+\w+){0,3}
This will need some finetuning to take account of all possible punctuations, and other weird stuff of language that does not go well with the "word followed by space/comma,etc" schema. Take a look at the ASCII character classes, probably they will come handy.
const test_str = ` The most popular chicken's restaurant closed tonight because of lot of complain about chicken taste, all the employee lost their jobs`;
function mySearchFunc(str, lookup) {
const regex = new RegExp("(?:\\w+[\\s,;:'\".!?]+){0,3}" + lookup + "(?:[\\s,;:'\".!?]+\\w+){0,3}", "gm");
let m;
let result = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m)
//console.log(`Found: ${m}`);
result.push(m[0]);
}
return result.join(' ... ');
}
console.log(mySearchFunc(test_str, "chicken"));
Related
How can I change the function count() to get the proper out put.
This is the function
<div id="randomtxt">
The red glow of tail lights indicating another long drive home from work after an even longer 24-hour shift at the hospital. The shift hadn’t been horrible but the constant stream of patients entering the ER meant there was no downtime. She had some of the “regulars” in tonight with new ailments they were sure were going to kill them. It’s amazing what a couple of Tylenol and a physical exam from the doctor did to eliminate their pain, nausea, headache, or whatever other mild symptoms they had. Sometimes she wondered if all they really needed was some interaction with others and a bit of the individual attention they received from the nurses.
<br />
<br />
After hunting for several hours, we finally saw a large seal sunning itself on a flat rock. I took one of the wooden clubs while Larry took the longer one. We slowly snuck up behind the seal until we were close enough to club it over its head. The seal slumped over and died. This seal would help us survive. We could eat the meat and fat. The fat could be burned in a shell for light and the fur could be used to make a blanket. We declared our first day of hunting a great success.
<br />
<br />
Love isn't always a ray of sunshine. That's what the older girls kept telling her when she said she had found the perfect man. She had thought this was simply bitter talk on their part since they had been unable to find true love like hers. But now she had to face the fact that they may have been right. Love may not always be a ray of sunshine. That is unless they were referring to how the sun can burn.
</div>
But i don't know how to change my function and get a out put like this
console.log(count_occurence( text,"the" )); //Output expected "20"
console.log(count_occurence( text,"of" )); //Output expected "9"
console.log(count_occurence( text,"from" )); //Output expected "3"
I used the second parameter as a filter, which compares every word with it and when it's true, it's getting passed into the return array.
const randomText = "In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix"
function countWords(text, filter = ''){
const words = {}
text.split(' ').filter(word => {
if(typeof filter == 'string' && filter.length > 0){
return word === filter
}
else return true
}).forEach(word => {
if(!(Object.keys(words).includes(word))) {
words[word] = 1
}
else words[word]++
})
return words
}
console.log(countWords(randomText, 'a'))
You passed 'is' as text, the filter is second parameter
const randomText = "In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix"
var txt = randomText.toLowerCase()
function countOccurence(text, occurence) {
var div = text.toLowerCase().split(/[^a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]/);
const words = {}
div.filter(word => {
if(typeof occurence == 'string' && occurence.length > 0){
return word === occurence
}
else return true
}).forEach(word => {
if(!(Object.keys(words).includes(word))) {
words[word] = 1
}
else words[word]++
})
return words
}
console.log(Object.values(countOccurence(randomText, "is")))
I want to unit-test a function that returns a complex nested data structure, but I'm only interested in certain fields of that structure. For example:
expectedResult = Right (
UserRecord {
name = "someName",
id = <don't care>
address = AddressRecord {
street = "someStreet",
id = <don't care>
}
}
)
Is there a generic way to assert a result of the above form in HSpec? That is, some way to write an expression
result `shouldBe` expectedResult
where I do not need to specify those parts of the expected result that I am not interested in? I found this answer, which requires to copy over all don't care fields from result to expectedResult; this might get rather tedious. Maybe there is a standard approach using lenses? Or some library with assertion helpers I haven't heard of?
A simple approach:
result `shouldSatisfy` \a ->
name a == "someName" &&
street (address a) == "someStreet"
I was trying to write an array which has classes that are "search queries" and I'm writing a for in loop that goes through them and picks out keywords using .rangeOfString:
import UIKit
var str = "Hello, playground"
class Search {
var searchQuery:String
init (query:String) {
self.searchQuery = query
}
}
var innocent = 0
var suspicious = 0
let keyword = "terrorist"
let queries = [Search(query: "How to be a terrorist"), Search(query: "How to join
Islamic State"), Search(query: "I want to be an astronaut")]
for query in queries {
if (query.searchQuery.rangeOfString(keyword) != nil){
suspicious++
}
else {
innocent++
}
}
print(suspicious)
I want to make it such that I can have more than one keyword (e.g Islamic State and terrorist) so if it detects either of these it increments suspicious, but I can't apply an OR operator to two strings for some reason, not sure why. Does anyone have any idea how this may be possible in Swift?
I'm new to Swift and my programming is rusty in general, so any tips on how to improve this code in general (is there another, better way to do this besides .rangeOfString, how would filtering through search queries actually be done in real life in search engines?) is much appreciated. Thank you!
IF I have an array, names = ['Jon', 'Stewart', 'Oliver'], I want to get all 3-tuples and 2-tuples:
Jon, Stewart, Oliver
Jon, Stewart
Stewart, Oliver
Oliver, Jon
What algorithm can I use for this? The array can also be VERY large (200+ items), so whatever code I use should be asynchronous in nature.
I think you might be confusing "asynchronous" here. The process of creating the tuples will always block. So possibly what you'll want to do is create an algorithm that only generates a tuple when it's required, based on some parameters, then cache it for later.
Since you've tagged this as node.js I'm going to assume that's the programming language of interest. Based on that assumption, and the assumption that you actually don't want this to be blocking, your best bet is to spawn multiple processes and pipe out the process creating these tuples. Here's a very rough example script (emphasis on rough):
var cluster = require('cluster');
var names = ['Jon', 'Stewart', 'Oliver'];
if (cluster.isWorker) {
var count = +process.env.tupple_count;
var tuples = [];
// Process tuple here, then return it.
process.send(JSON.stringify(tuples));
return;
}
cluster.fork({ tupple_count: 2 }).on('message', function(msg) {
// Receive tuple here:
var tuple = JSON.parse(msg);
console.log(tuple);
});
// Go about my life.
Then you could write a general algorithm to return these. Here's a good link on how to do this: Algorithm to return all combinations of k elements from n
I hope this is the right place to post this. I'm a web designer who is doing a site for a client, except for their store location page, which I have contracted out to a Google map developer. The map needs to be searchable by lat and long, in both decimal and degrees/minutes/seconds. The programmer has it set up only for decimal, and says it will be a good deal of effort to make the search use both types.
Being a web designer myself, I know sometimes changes can take a while. However, I want to be sure what the programmer is saying is correct. I know that when I search Google maps in general, it can accept both types of lat and long measurements. I thought therefore, that a map customized to search lat and long via Google maps would also do this. Is that a correct assumption? Or could it potentially involve a good deal of work to make this happen? Should the programmer have assumed it would be searchable in both types of lat long?
Thank you for any feedback!
It does involve some work, but it's not that difficult to do:
function deg_to_dms (deg) {
var d = Math.floor (deg);
var minfloat = (deg-d)*60;
var m = Math.floor(minfloat);
var secfloat = (minfloat-m)*60;
var s = Math.round(secfloat);
// After rounding, the seconds might become 60. These two
// if-tests are not necessary if no rounding is done.
if (s==60) {
m++;
s=0;
}
if (m==60) {
d++;
m=0;
}
return ("" + d + ":" + m + ":" + s);
}