How to write a simple script to read text from a file and compute the number of sentences,...

H

HansDev

I just finished a challenge (noted above) and I was wondering how good is this approach or is there some simpler solution that I am not aware of?

If you have a different solution, try to explain the code for people less experienced than myself rather just than pasting a solution.

Here is an example text file to be read from:

This file has eight words in this sentence.
There are two sentences. In this paragraph.

And two paragraphs in total.
Lorem ispsum.
Lorem ispsum.
Lorem ispsum.
Lorem ispsum.


/**
* Write a simple script to read text from a file and compute (approximately) the number of sentences, number of unique words and punctuation/symbols.
* Run the code with node ./problem-2.js test.txt
*/

// Use Node's builtin api to read a file
const fs = require('fs');

//#1 count the number of words
const wordCount = (string) => string.split(" ").length;

//#2 count the number of unique words
const uniqueWords = txt => new Set(txt.toLowerCase().match(/\w+/g)).size;

//#3 count the number of paragraphs
const paragraphCount = (paragraphString) =>{
//seperate each sentence into a seperate string
paragraphString = paragraphString.split("\n\n");
// console.table(paragraphString) // show as a table for better visual
let paragraphArray = paragraphString.length; // length of paragraph array

let paragraphCount = 0;
let strip_whitespace = /\s+/gi;
while (paragraphArray >=0) {
paragraphArray--;
let tmp = paragraphString[paragraphArray];
tmp = tmp ? tmp .replace(strip_whitespace,"") : tmp;

if( tmp && tmp.length > 1 ) paragraphCount++;
}
return paragraphCount;
}

function countPunctuations(punctuationsStrings) {
let punctuationsCount = 0;
const punctuations = [".", ",", "!", "?"];
// const symbols = ["~","`","!","@","#","$","%","^","&","*","(",")","_","+","-","=","{","}","|","[","]","\",":",";","'","<",]","?","/",]
for (const ch of punctuationsStrings) {
if (punctuations.includes(ch)) punctuationsCount++;
}
return punctuationsCount;
}

fs.readFile("test-2.txt", 'utf8', function(err, data) {
if (err) throw err;
console.log("The text in the file:\n\n", data,"\n")
// store results in an object to present the log better
let result={
"word count": wordCount(data),
"unique words": uniqueWords(data),
"paragraph count": paragraphCount(data),
"punctuation count": countPunctuations(data),
}
console.table(result)
});
```
 

Unreplied Threads

Does moderating a conference panel go on a CV?

  • David_Ave
  • Education
  • Replies: 0
Should moderating conference panels go on an academic CV and, if so, where? I am in a humanities-related field, if that matters.

Thank you!

Hedging exotic options

  • Kapes Mate
  • Finance
  • Replies: 0
How can exotic and other path dependent, such as asian options be hedged? For example in the case of an asian option, what is the replicating portfolio: what instruments to keep in it and “how much”?

It is known from the standard Black-Scholes model that when we replicate a vanilla European we have to hold $\Delta_{t}$ (the partial derivative of the option PV corresponding to the variable of the stock price) underlying in every $t$, but how is the replication of an asian option (or any other exotic option) maintained in theory/practice?

In general, literature firstly always discuss what the price of an option is as calculating a tipically very tough expectation. It is always good to know what the price is, but the other important question is how to hedge these options, i.e. what strategy to use in order to construct a replicating portfolio. I think this second question is rarely discussed, even though it is probably more important then knowing the price. (Additionally, in my opinion determining the price is also part of the “strategy”, but it is just my opinion.)

Driving a mosfet with optocoupler and a voltage source between 5V to 60V

  • Delfino
  • Physics
  • Replies: 0
I am studying how to design an optocoupled active load, and I need to control the MOSFET with the signal obtained from a 4n25. The voltage that will be used at the gate will come from the load to be tested, so it will range from 5V (or 10V) to 60V.

What would be the best way to make the driver for these active load mosfets?

A ideia about drive circuit: enter image description here

The circuit on the LED side is not powered by a PWM source, but by a set of opamps that will provide the current level necessary to activate or not the mosfet through the 4n25.

What is wrong with my Dmux8way? How can I fix it?

  • Sonya Lyu
  • Physics
  • Replies: 0
enter image description here

The problem is something with the sel spliter and the leftmost DMUX4WAY, the automatic check returned - "have different bit width and cannot be connected". But I don’t know how can I fix it. Please help me with that.

Como fazer para o gitignore, ignorar determinado arquivo depois dele ter sidos adiconados no committ

Fiz a adição dos arquivos do meu código por meio do git add ., porém só adicionei o .gitignore para ignorar as bibliotecas do ambiente virtual depois dos arquivos serem adicionados. No vscode a letra U que aparecia do lado dos arquivos foram substituídas pela letra A. Quando eu enviar para o repositório do github, estas bibliotecas do do ambiente virtual serão ignoradas mesmo ter sido adicionado o .gitignore depois? Eu não gostaria de enviar um arquivo gigante para o github. Obrigada!

universal structures over $\mathcal A_g$

  • Aitor Iribar Lopez
  • Mathematics
  • Replies: 0
Over the moduli space of curves, $\overline{\mathcal{M}}_{g,n}$ there are several "natural" spaces like the universal curve, the universal Jacobian, the space of stable maps, the universal space of semistable bundles, the universal Quot scheme...

Is there some space of this form over $\mathcal A_g$ apart from the universal abelian variety, its $k$-fold products and the Poincare bundle?

You can't tell me the US lacks –

Empty crossword grid
Solve on Penpa+

Across
1. Wyoming national park managed only wee slot (11)
9. Florida public housing clerk in Springfield mart (3)
10. California city cops regularly dropped somewhere in Southeast Asia (4)
12. New Mexico inhabitant's article describing love for Christmas song (4)
13. South Dakota mountain area in poverty – hotel drowning in bills (5,5)
14. South Carolina region – endless terror! (5)
17. Colorado wants what starts seven geographical answers here, and that is disturbing (3)
18. California coastal area's mountains guarded by old nobleman east of Monterey (6,6)
21. West Virginia retreats given no promise (3)
23. California event, one of several hosted in 18 across, with classical art? (6)
27. Washington landmark described by Caucasian doctor on TV (5,5)
28. Delaware plantation has to create a new strategy (6)
31. Washington concerts finally happened (3)
32. California city's headed with bronco that's going wild (7,5)
34. Michigan's chief attends country club to see Australian runner (3)
38. Utah institute ultimately led by British savage (5)
42. North Carolina city's political party takes on debt, I hear (10)
43. Pennsylvania's once excellent museum initially displayed work of art (4)
44. Texas export found beyond southern land (4)
45. Georgia retired couple's stern and mature (3)
46. Rhode Island school is disgusting, shipping student to city on the Mexican border (11)

Down
1. Vegetables grown in the tropics coming up the fourth of this month (4)
2. Brazilian politician is fully upset after being interrupted by union leader (4)
3. Hide to strike the tragic king (4)
4. Weak breaking waves (4)
5. Part of Hong Kong that's very fashionable? Not entirely (4)
6. Exclusively covering legendary coat (4)
7. Louisiana city associated with Nollywood's #1 director, Christopher (5)
8. Metal ring gifted to partner (5)
11. Almost sick to intercept cry for help for Minutemen kept in these? (5)
15. Cameron who filmed someone shouting "Show me the money!" in fight inside church (5)
16. For example, goose's origin (3)
18. Up and down again (4)
19. Arrest in a criminal lair's starting (4)
20. Swimmer's partner has no right (4)
22. SHIELD agent caught villain in the end (4)
24. Chicago player is on constant amount of sugar (4)
25. Once more, perform or write a review? (5)
26. Sitting principals in school expecting silence (4)
29. Europeans beginning to come down mountains (5)
30. Point preceding King's decline (3)
32. Gets note in connection with hot tub toppling over (5)
33. German artist purred surprisingly when pressure was taken off (5)
35. Record group of people with shared characteristics in purposeful destruction (4)
36. Mysterious writer's accepted works lacking their initial character (4)
37. Egyptian deity is shown on top of its exact copy (4)
39. Enterprise counsellor dropping trou, primarily to get bread (4)
40. Ancient city situated atop a large mountain chain (4)
41. Blade is perplexed, not oddly (4)
Top