স্ট্রিংয়ে শব্দ গণনা করা হচ্ছে


93

আমি একটি লেখায় শব্দগুলি এইভাবে গণনা করার চেষ্টা করছিলাম:

function WordCount(str) {
  var totalSoFar = 0;
  for (var i = 0; i < WordCount.length; i++)
    if (str(i) === " ") { // if a space is found in str
      totalSoFar = +1; // add 1 to total so far
  }
  totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words
}

console.log(WordCount("Random String"));

আমি মনে করি আমি ifবিবৃতিটি ভুল বলে মনে করি ব্যতীত আমি এটি বেশ ভালভাবে পেয়েছি । যে অংশটি str(i)একটি স্থান রয়েছে কিনা তা পরীক্ষা করে এবং 1 যোগ করে।

সম্পাদনা করুন:

আমি খুঁজে পেয়েছি (ব্লেন্ডারের জন্য ধন্যবাদ) যে আমি অনেক কম কোড দিয়ে এটি করতে পারি:

function WordCount(str) { 
  return str.split(" ").length;
}

console.log(WordCount("hello world"));

str.split(' ').lengthএকটি সহজ পদ্ধতি হবে না ? jsfiddle.net/j08691/zUuzd
j08691

অথবা str.split(' ')এবং তারপরে 0 দৈর্ঘ্যের স্ট্রিং নয় এমনগুলি গণনা করুন?
কেটি কিলিয়ান

8
স্ট্রিং.স্প্লিট ('')। দৈর্ঘ্য কাজ করে না। স্পেস সবসময় শব্দের সীমানা হয় না! যদি দুটি শব্দের মধ্যে একাধিক স্থান থাকে? কি সম্পর্কে ". . ." ?
আলসো

আলসো যেমন বলেছিলেন, এই পদ্ধতিটি কাজ করবে না।
বাস্তবতা-টরেন্ট

4
@ রিয়েলিটি-টরেন্ট এটি একটি পুরানো পোস্ট।
cst1992

উত্তর:


109

স্কয়ার বন্ধনী ব্যবহার করুন, বন্ধনী নয়:

str[i] === " "

বা charAt:

str.charAt(i) === " "

আপনি এটি দিয়ে এটি করতে পারেন .split():

return str.split(' ').length;

আমি মনে করি আপনি যা বলছেন তা পেয়েছি কি আমার সম্পাদিত মূল প্রশ্নের উপরে আমার কোডটি ঠিক আছে?

শব্দটি স্থান অক্ষর ব্যতীত অন্য কোনও কিছুর দ্বারা সীমাবদ্ধ যেখানে আপনার সমাধান কাজ করবে? নিউলাইন বা ট্যাব দ্বারা বলুন?
নেমেসিসফিক্সেক্স

7
@ ব্লেন্ডার ভাল সমাধান তবে এটি স্ট্রিংয়ে বাদ দেওয়া ডাবল স্পেসের জন্য ভুল ফলাফল দিতে পারে ..
ipalibowhyte

95

চাকার পুনরায় উদ্ভাবনের আগে এগুলি ব্যবহার করে দেখুন

জাভাস্ক্রিপ্ট ব্যবহার করে স্ট্রিংয়ে শব্দের সংখ্যা গণনা থেকে

function countWords(str) {
  return str.trim().split(/\s+/).length;
}

http://www.mediacolleg.com/internet/javascript/text/count-crc.html থেকে

function countWords(s){
    s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude  start and end white-space
    s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
    s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
    return s.split(' ').filter(function(str){return str!="";}).length;
    //return s.split(' ').filter(String).length; - this can also be used
}

থেকে ব্যবহারের জাভাস্ক্রিপ্ট একটি স্ট্রিং শব্দের গণনা করার জন্য একটি Regex ব্যবহার না করেই - এই শ্রেষ্ঠ পদ্ধতির হতে হবে

function WordCount(str) {
     return str.split(' ')
            .filter(function(n) { return n != '' })
            .length;
}

লেখকের কাছ থেকে নোটস:

আপনি যেকোন উপায়ে শব্দ গণনা করতে এই স্ক্রিপ্টটি মানিয়ে নিতে পারেন। গুরুত্বপূর্ণ অংশটি হ'ল s.split(' ').length- এটি স্থানগুলি গণনা করে। স্ক্রিপ্ট গণনার আগে সমস্ত অতিরিক্ত স্পেস (ডাবল স্পেস ইত্যাদি) সরিয়ে ফেলার চেষ্টা করে। যদি পাঠ্যের মধ্যে দুটি শব্দ থাকে যার মধ্যে একটি স্পেস না থাকে তবে এটি তাদের একটি শব্দ হিসাবে গণ্য করবে, যেমন "প্রথম বাক্য। পরবর্তী বাক্যটি শুরু করুন"।


Ive এই সিনট্যাক্সটি কখনও দেখেনি: s = s.replace (/ (^ \ s *) | (\ s * $) / gi, "")); s = s.replace (/ [] {2,} / gi, ""); s = s.replace (/ \ n /, "\ n"); প্রতিটি লাইন মানে কি? এত অভাবী হওয়ার জন্য দুঃখিত

কিছু? এই কোডটি খুব বিভ্রান্তিকর এবং সেই ওয়েবসাইটটি যা আপনি আক্ষরিকভাবে অনুলিপি করেছেন এবং এটি থেকে আটকিয়েছিলেন তা মোটেই সহায়ক নয়। আমি যে কিছু পেয়েছি তার চেয়ে আমি আরও বেশি বিভ্রান্ত হয়েছি যে এটি আমাদের ডাবল স্পেসগুলি ফাঁকা ছাড়াই শব্দগুলির জন্য চেক করা উচিত তবে কিভাবে? মাত্র এক মিলিয়ন এলোমেলোভাবে রক্ষিত অক্ষরগুলি সত্যই সহায়তা করে না ...

আমি আপনাকে যা চেয়েছিলাম তা হ'ল আপনার লিখিত কোডটি ব্যাখ্যা করার জন্য। I এর আগে সিনট্যাক্সটি কখনও দেখেনি এবং এর অর্থ কী তা জানতে চেয়েছিল। এটা ঠিক আছে আমি একটি পৃথক প্রশ্ন করেছি এবং কেউ আমার প্রশ্নের গভীরতার উত্তর দিয়েছে। এত কিছু চাওয়ার জন্য দুঃখিত।

4
str.split (/ \ s + /)। দৈর্ঘ্য সত্যিকারের মতো কাজ করে না: সাদা স্থানকে পিছনে রেখে অন্য শব্দ হিসাবে বিবেচনা করা হয়।
আয়ান

4
নোট করুন এটি খালি ইনপুটটির জন্য 1 প্রদান করে।
পাই 6 কে

21

স্ট্রিংয়ে শব্দ গণনা করার আরও একটি উপায়। এই কোডটি এমন শব্দের গণনা করে যা কেবলমাত্র বর্ণানুক্রমিক অক্ষর এবং "_", "" "," - "," "" অক্ষর রাখে।

function countWords(str) {
  var matches = str.match(/[\w\d\’\'-]+/gi);
  return matches ? matches.length : 0;
}

4
’'-"বিড়ালের মিয়া" 3 শব্দ হিসাবে গণনা না করে যাতে যুক্ত করার বিষয়টিও বিবেচনা করতে পারে । এবং "ইন-এর মধ্যে"
এমপেন

@ পরামর্শের জন্য ধন্যবাদ। আমি আমার উত্তরটি অনুযায়ী আপডেট করেছি।
অ্যালেক্স

আমার স্ট্রিংয়ের প্রথম
চরটি

4
আপনাকে ’'একটি রেজেক্সে পালানোর দরকার নেই । /[\w\d’'-]+/giESLint অ-অকার্যকর-পালানোর সতর্কতাগুলি এড়াতে ব্যবহার করুন
স্টিফান ব্লেম্বার্গ

18

স্ট্রিং পরিষ্কার করার পরে, আপনি অ-হোয়াইটস্পেস অক্ষর বা শব্দ-সীমার সাথে মিলিয়ে নিতে পারেন।

স্ট্রিংয়ে শব্দগুলি ক্যাপচারের জন্য এখানে দুটি সাধারণ নিয়মিত এক্সপ্রেশন:

  • অ-সাদা-স্থানের অক্ষরের ক্রম: /\S+/g
  • শব্দ সীমার মধ্যে বৈধ অক্ষর: /\b[a-z\d]+\b/g

নীচের উদাহরণটিতে দেখানো হয়েছে কীভাবে এই ক্যাপচারিং নিদর্শনগুলি ব্যবহার করে একটি স্ট্রিং থেকে শব্দ গণনা পুনরুদ্ধার করা যায়।

/*Redirect console output to HTML.*/document.body.innerHTML='';console.log=function(s){document.body.innerHTML+=s+'\n';};
/*String format.*/String.format||(String.format=function(f){return function(a){return f.replace(/{(\d+)}/g,function(m,n){return"undefined"!=typeof a[n]?a[n]:m})}([].slice.call(arguments,1))});

// ^ IGNORE CODE ABOVE ^
//   =================

// Clean and match sub-strings in a string.
function extractSubstr(str, regexp) {
    return str.replace(/[^\w\s]|_/g, '')
        .replace(/\s+/g, ' ')
        .toLowerCase().match(regexp) || [];
}

// Find words by searching for sequences of non-whitespace characters.
function getWordsByNonWhiteSpace(str) {
    return extractSubstr(str, /\S+/g);
}

// Find words by searching for valid characters between word-boundaries.
function getWordsByWordBoundaries(str) {
    return extractSubstr(str, /\b[a-z\d]+\b/g);
}

// Example of usage.
var edisonQuote = "I have not failed. I've just found 10,000 ways that won't work.";
var words1 = getWordsByNonWhiteSpace(edisonQuote);
var words2 = getWordsByWordBoundaries(edisonQuote);

console.log(String.format('"{0}" - Thomas Edison\n\nWord count via:\n', edisonQuote));
console.log(String.format(' - non-white-space: ({0}) [{1}]', words1.length, words1.join(', ')));
console.log(String.format(' - word-boundaries: ({0}) [{1}]', words2.length, words2.join(', ')));
body { font-family: monospace; white-space: pre; font-size: 11px; }


অনন্য শব্দ সন্ধান করা

আপনি স্বতন্ত্র গণনা পেতে শব্দের একটি ম্যাপিংও তৈরি করতে পারেন।

function cleanString(str) {
    return str.replace(/[^\w\s]|_/g, '')
        .replace(/\s+/g, ' ')
        .toLowerCase();
}

function extractSubstr(str, regexp) {
    return cleanString(str).match(regexp) || [];
}

function getWordsByNonWhiteSpace(str) {
    return extractSubstr(str, /\S+/g);
}

function getWordsByWordBoundaries(str) {
    return extractSubstr(str, /\b[a-z\d]+\b/g);
}

function wordMap(str) {
    return getWordsByWordBoundaries(str).reduce(function(map, word) {
        map[word] = (map[word] || 0) + 1;
        return map;
    }, {});
}

function mapToTuples(map) {
    return Object.keys(map).map(function(key) {
        return [ key, map[key] ];
    });
}

function mapToSortedTuples(map, sortFn, sortOrder) {
    return mapToTuples(map).sort(function(a, b) {
        return sortFn.call(undefined, a, b, sortOrder);
    });
}

function countWords(str) {
    return getWordsByWordBoundaries(str).length;
}

function wordFrequency(str) {
    return mapToSortedTuples(wordMap(str), function(a, b, order) {
        if (b[1] > a[1]) {
            return order[1] * -1;
        } else if (a[1] > b[1]) {
            return order[1] * 1;
        } else {
            return order[0] * (a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0));
        }
    }, [1, -1]);
}

function printTuples(tuples) {
    return tuples.map(function(tuple) {
        return padStr(tuple[0], ' ', 12, 1) + ' -> ' + tuple[1];
    }).join('\n');
}

function padStr(str, ch, width, dir) { 
    return (width <= str.length ? str : padStr(dir < 0 ? ch + str : str + ch, ch, width, dir)).substr(0, width);
}

function toTable(data, headers) {
    return $('<table>').append($('<thead>').append($('<tr>').append(headers.map(function(header) {
        return $('<th>').html(header);
    })))).append($('<tbody>').append(data.map(function(row) {
        return $('<tr>').append(row.map(function(cell) {
            return $('<td>').html(cell);
        }));
    })));
}

function addRowsBefore(table, data) {
    table.find('tbody').prepend(data.map(function(row) {
        return $('<tr>').append(row.map(function(cell) {
            return $('<td>').html(cell);
        }));
    }));
    return table;
}

$(function() {
    $('#countWordsBtn').on('click', function(e) {
        var str = $('#wordsTxtAra').val();
        var wordFreq = wordFrequency(str);
        var wordCount = countWords(str);
        var uniqueWords = wordFreq.length;
        var summaryData = [
            [ 'TOTAL', wordCount ],
            [ 'UNIQUE', uniqueWords ]
        ];
        var table = toTable(wordFreq, ['Word', 'Frequency']);
        addRowsBefore(table, summaryData);
        $('#wordFreq').html(table);
    });
});
table {
    border-collapse: collapse;
    table-layout: fixed;
    width: 200px;
    font-family: monospace;
}
thead {
    border-bottom: #000 3px double;;
}
table, td, th {
    border: #000 1px solid;
}
td, th {
    padding: 2px;
    width: 100px;
    overflow: hidden;
}

textarea, input[type="button"], table {
    margin: 4px;
    padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h1>Word Frequency</h1>
<textarea id="wordsTxtAra" cols="60" rows="8">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.

But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.</textarea><br />
<input type="button" id="countWordsBtn" value="Count Words" />
<div id="wordFreq"></div>


4
এটি একটি দুর্দান্ত এবং বিস্তৃত উত্তর। সমস্ত উদাহরণের জন্য ধন্যবাদ, তারা সত্যিই দরকারী!
কনার

14

আমি মনে করি এই পদ্ধতিটি আপনার চেয়ে বেশি

var getWordCount = function(v){
    var matches = v.match(/\S+/g) ;
    return matches?matches.length:0;
}

7

String.prototype.match একটি অ্যারে প্রদান করে, আমরা তারপরে দৈর্ঘ্যটি পরীক্ষা করতে পারি,

আমি এই পদ্ধতিটি সবচেয়ে বর্ণনামূলক বলে মনে করি

var str = 'one two three four five';

str.match(/\w+/g).length;

4
স্ট্রিং ফাঁকা থাকলে একটি ত্রুটি হওয়ার সম্ভাব্য জায়গা
পূর্বখালো অ্যালেক্স

5

আমি এখন পর্যন্ত খুঁজে পাওয়া সবচেয়ে সহজ উপায় হ'ল বিভক্ত হয়ে একটি রেজিেক্স ব্যবহার করা।

var calculate = function() {
  var string = document.getElementById('input').value;
  var length = string.split(/[^\s]+/).length - 1;
  document.getElementById('count').innerHTML = length;
};
<textarea id="input">My super text that does 7 words.</textarea>
<button onclick="calculate()">Calculate</button>
<span id="count">7</span> words


3

@ 7-ইসনটবাদ দ্বারা প্রদত্ত উত্তরটি অত্যন্ত নিকটে, তবে একক-শব্দ লাইন গণনা করে না। এখানে স্থিরতা রয়েছে যা শব্দ, স্পেস এবং নিউলাইনগুলির প্রতিটি সম্ভাব্য সংমিশ্রণের জন্য অ্যাকাউন্ট হিসাবে মনে হয়।

function countWords(s){
    s = s.replace(/\n/g,' '); // newlines to space
    s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
    s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
    return s.split(' ').length; 
}

3

এখানে আমার পদ্ধতির, যা খালি ফাঁক দিয়ে একটি স্ট্রিং বিভক্ত হয়, তারপরে অ্যারের লুপ করে এবং গণনা বাড়িয়ে দেয় যদি অ্যারে [i] প্রদত্ত রেজেক্স প্যাটার্নের সাথে মেলে।

    function wordCount(str) {
        var stringArray = str.split(' ');
        var count = 0;
        for (var i = 0; i < stringArray.length; i++) {
            var word = stringArray[i];
            if (/[A-Za-z]/.test(word)) {
                count++
            }
        }
        return count
    }

অনুরোধ করা হয়েছে:

var str = "testing strings here's a string --..  ? // ... random characters ,,, end of string";
wordCount(str)

(ফাংশনের যথার্থতা দেখানোর জন্য অতিরিক্ত অক্ষর এবং স্পেস যুক্ত করা হয়েছে)

উপরের আরআরটি 10 ​​প্রদান করে, যা সঠিক!


কিছু কিছু ভাষা একেবারেই ব্যবহার [A-Za-z]করে না
ডেভিড

3

এটি সমস্ত ক্ষেত্রে পরিচালনা করবে এবং যথাসম্ভব দক্ষ। (আপনি বিচ্ছেদ চান না ('') যদি না আপনি আগেই জানেন যে একের চেয়ে বেশি দৈর্ঘ্যের কোনও স্থান নেই)):

var quote = `Of all the talents bestowed upon men, 
              none is so precious as the gift of oratory. 
              He who enjoys it wields a power more durable than that of a great king. 
              He is an independent force in the world. 
              Abandoned by his party, betrayed by his friends, stripped of his offices, 
              whoever can command this power is still formidable.`;

function WordCount(text) {
    text = text.trim();
    return text.length > 0 ? text.split(/\s+/).length : 0;
}
console.log(WordCount(quote));//59
console.log(WordCount('f'));//1
console.log(WordCount('  f '));//1
console.log(WordCount('   '));//0

2

এটি করার জন্য আরও কার্যকর উপায় থাকতে পারে তবে এটি আমার জন্য কাজ করেছে।

function countWords(passedString){
  passedString = passedString.replace(/(^\s*)|(\s*$)/gi, '');
  passedString = passedString.replace(/\s\s+/g, ' '); 
  passedString = passedString.replace(/,/g, ' ');  
  passedString = passedString.replace(/;/g, ' ');
  passedString = passedString.replace(/\//g, ' ');  
  passedString = passedString.replace(/\\/g, ' ');  
  passedString = passedString.replace(/{/g, ' ');
  passedString = passedString.replace(/}/g, ' ');
  passedString = passedString.replace(/\n/g, ' ');  
  passedString = passedString.replace(/\./g, ' '); 
  passedString = passedString.replace(/[\{\}]/g, ' ');
  passedString = passedString.replace(/[\(\)]/g, ' ');
  passedString = passedString.replace(/[[\]]/g, ' ');
  passedString = passedString.replace(/[ ]{2,}/gi, ' ');
  var countWordsBySpaces = passedString.split(' ').length; 
  return countWordsBySpaces;

}

এটি নিম্নলিখিত শব্দগুলিকে পৃথক শব্দ হিসাবে স্বীকৃতি দিতে সক্ষম:

abc,abc= 2 শব্দ,
abc/abc/abc= 3 টি শব্দ (এগিয়ে এবং পিছিয়ে থাকা স্ল্যাশ নিয়ে কাজ করে),
abc.abc= 2 শব্দ,
abc[abc]abc= 3 শব্দ,
abc;abc= 2 শব্দ,

(কিছু অন্যান্য পরামর্শ যা আমি উপরের প্রতিটি উদাহরণকে কেবল 1 এক্স শব্দ হিসাবে গণনা করার চেষ্টা করেছি) এটিও:

  • সমস্ত নেতৃস্থানীয় এবং অনুসরণকারী শ্বেত স্থান উপেক্ষা করে

  • গন্য একটি একক অক্ষর নতুন লাইন দ্বারা অনুসরণ, একটি শব্দ হিসাবে - যা আমি এই পৃষ্ঠাতে দেওয়া প্রস্তাবনার কিছু পেয়েছি গণনা করা হয় না, উদাহরণস্বরূপ:
    একটি
    একটি
    একটি
    একটি
    একটি
    কখনও কখনও 0 এক্স শব্দ হিসাবে গণনা পায়, এবং অন্যান্য ক্রিয়াকলাপগুলি কেবল 5 x শব্দের পরিবর্তে 1 x শব্দ হিসাবে গণনা করে)

যদি কারও কাছে কীভাবে এটি উন্নত করা যায় সে সম্পর্কে কোনও ধারণা থাকে বা ক্লিনার / আরও দক্ষ - তবে দয়া করে আপনাকে 2 সেন্ট যোগ করুন! এই কেউ সাহায্য করে আউট আশা করি.


2
function countWords(str) {
    var regEx = /([^\u0000-\u007F]|\w)+/g;  
    return str.match(regEx).length;
}

ব্যাখ্যা:

/([^\u0000-\u007F]|\w)শব্দের অক্ষরের সাথে মেলে - যা দুর্দান্ত -> রেজেক্স আমাদের জন্য ভারী উত্তোলন করে। (এই প্যাটার্নটি নিম্নলিখিত এসও উত্তরের উপর ভিত্তি করে: https://stackoverflow.com/a/35743562/1806956 @ ল্যান্ডিও দ্বারা)

+ পূর্বনির্ধারিত শব্দের অক্ষরের পুরো স্ট্রিংয়ের সাথে মেলে - তাই আমরা মূলত শব্দ অক্ষরগুলিকে গ্রুপ করি।

/g এর অর্থ এটি শেষ অবধি তাকিয়ে থাকে।

str.match(regEx) পাওয়া শব্দের একটি অ্যারে প্রদান করে - তাই আমরা এর দৈর্ঘ্য গণনা করি।


4
জটিল রেইজেক্স হ'ল ডাইনিট্র্যাক্টের শিল্প। একটি উচ্চারণ আমরা উচ্চারণ করতে শিখি, তবে এর কারণ জিজ্ঞাসা করার সাহস কখনও নেই। ভাগ করার জন্য আপনাকে ধন্যবাদ।
ব্লেইজ

^ এটি একটি দারুণ উক্তি
r3wt

আমি এই ত্রুটিটি পাচ্ছি: ত্রুটি অনাকাঙ্ক্ষিত নিয়ন্ত্রণ অক্ষর নিয়মিত অভিব্যক্তিতে:
00

যদি এই স্ট্রিংটি / বা (
ওয়াল্টার মনেক্কে

@ ওয়াল্টারমোনস্কে এটি কেবল ক্রোমে পরীক্ষা করেছে - ত্রুটিটি পেল না। এটি দিয়ে আপনি কোথায় ত্রুটি পেয়েছেন? ধন্যবাদ
রোনেন রাবিনোভিসি

2

যারা লোডাশ ব্যবহার করতে চান তাদের জন্য এই _.wordsফাংশনটি ব্যবহার করতে পারেন :

var str = "Random String";
var wordCount = _.size(_.words(str));
console.log(wordCount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


2

নির্ভুলতাও গুরুত্বপূর্ণ।

3 বিকল্পটি কী করে তা হ'ল মূলত সমস্তটি তবে যে কোনও শ্বেতস্পেসগুলিকে একটি দিয়ে প্রতিস্থাপন করে +1তারপরে আপনাকে মূল্যায়ন 1শব্দের গণনা দেওয়ার জন্য এটি মূল্যায়ন করে ।

আমি এখানে যে চারটি করেছি তার এটি সবচেয়ে সঠিক এবং দ্রুততম পদ্ধতি।

দয়া করে মনে রাখবেন এটি return str.split(" ").length;মাইক্রোসফ্ট ওয়ার্ডের সাথে তুলনা করার চেয়ে ধীরে তবে এটি সঠিক।

নীচে নীচে ফাইল অপস / গুলি এবং ফিরে আসা শব্দ গণনা দেখুন।

এই বেঞ্চ পরীক্ষাটি চালানোর জন্য এখানে একটি লিঙ্ক। https://jsbench.me/ztk2t3q3w5/1

// This is the fastest at 111,037 ops/s ±2.86% fastest
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function WordCount(str) {
  return str.split(" ").length;
}
console.log(WordCount(str));
// Returns 241 words. Not the same as Microsoft Word count, of by one.

// This is the 2nd fastest at 46,835 ops/s ±1.76% 57.82% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function WordCount(str) {
  return str.split(/(?!\W)\S+/).length;
}
console.log(WordCount(str));
// Returns 241 words. Not the same as Microsoft Word count, of by one.

// This is the 3rd fastest at 37,121 ops/s ±1.18% 66.57% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function countWords(str) {
  var str = str.replace(/\S+/g,"\+1");
  return eval(str);
}
console.log(countWords(str));
// Returns 240 words. Same as Microsoft Word count.

// This is the slowest at 89 ops/s 17,270 ops/s ±2.29% 84.45% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function countWords(str) {
  var str = str.replace(/(?!\W)\S+/g,"1").replace(/\s*/g,"");
  return str.lastIndexOf("");
}
console.log(countWords(str));
// Returns 240 words. Same as Microsoft Word count.


1

এখানে একটি ফাংশন যা এইচটিএমএল কোডে শব্দের সংখ্যা গণনা করে:

$(this).val()
    .replace(/((&nbsp;)|(<[^>]*>))+/g, '') // remove html spaces and tags
    .replace(/\s+/g, ' ') // merge multiple spaces into one
    .trim() // trim ending and beginning spaces (yes, this is needed)
    .match(/\s/g) // find all spaces by regex
    .length // get amount of matches

1
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length

6
এই কোড স্নিপেট একটি ব্যাখ্যা সহ প্রশ্নটি সমাধান করতে পারে, যদিও সত্যিই আপনার পোস্টের মান উন্নত করতে সহায়তা করে। মনে রাখবেন যে আপনি ভবিষ্যতে পাঠকদের জন্য প্রশ্নের উত্তর দিচ্ছেন, এবং সেই লোকেরা আপনার কোড পরামর্শের কারণগুলি জানেন না।
ইসমা

1

আমি নিশ্চিত নই যে এটি আগে বলা হয়েছিল কিনা, বা এখানে যদি এটি প্রয়োজন হয় তবে আপনি স্ট্রিংটিকে একটি অ্যারে তৈরি করতে না পারেন এবং তারপরে দৈর্ঘ্যটি খুঁজে পেতে পারেন না?

let randomString = "Random String";

let stringWords = randomString.split(' ');
console.log(stringWords.length);

1

আমি মনে করি এই উত্তরটি এর জন্য সমস্ত সমাধান দেবে:

  1. প্রদত্ত স্ট্রিংয়ে অক্ষরের সংখ্যা
  2. প্রদত্ত স্ট্রিংয়ে শব্দের সংখ্যা
  3. প্রদত্ত স্ট্রিংয়ের লাইনের সংখ্যা

 function NumberOf() { 
		 var string = "Write a piece of code in any language of your choice that computes the total number of characters, words and lines in a given text. \n This is second line. \n This is third line.";

		 var length = string.length; //No of characters
		 var words = string.match(/\w+/g).length; //No of words
		 var lines = string.split(/\r\n|\r|\n/).length; // No of lines

		 console.log('Number of characters:',length);
		 console.log('Number of words:',words);
		 console.log('Number of lines:',lines);


}

NumberOf();

  1. প্রথমে আপনাকে প্রদত্ত স্ট্রিংয়ের দৈর্ঘ্য সন্ধান করতে হবে string.length
  2. তারপরে আপনি শব্দটির সাথে স্ট্রিংয়ের সাথে মিল রেখে সংখ্যার সন্ধান করতে পারেন string.match(/\w+/g).length
  3. শেষ পর্যন্ত আপনি প্রতিটি লাইন এভাবে বিভক্ত করতে পারেন string.length(/\r\n|\r|\n/).length

আমি আশা করি যারা এই 3 টি উত্তর অনুসন্ধান করছেন তাদেরকে এটি সহায়তা করতে পারে।


4
দুর্দান্ত। পরিবর্তনশীল নামটি stringঅন্য কোনওটিতে পরিবর্তন করুন to এটা বিভ্রান্তিকর. আমাকে এক সেকেন্ডের জন্য ভাবার কারণ string.match()এটি একটি স্থির পদ্ধতি। চিয়ার্স
লজ্জা আগম

হ্যাঁ !! নিশ্চিত @ শাইআগাম
লিএন

0
<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<script type="text/javascript">
var cnt;
function wordcount(count) {
var words = count.split(/\s/);
cnt = words.length;
var ele = document.getElementById('w_count');
ele.value = cnt;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>

0

আমি এটির দেরী জানি কিন্তু এই রেজেক্সটি আপনার সমস্যার সমাধান করা উচিত। এটি আপনার স্ট্রিংয়ের শব্দের সংখ্যার সাথে মিলবে এবং ফিরে আসবে। তারপরে আপনি যার সমাধান হিসাবে চিহ্নিত করেছেন, যা স্থান-স্পেস-শব্দটিকে 2 শব্দ হিসাবে গণনা করবে যদিও এটি সত্যই 1 শব্দ।

function countWords(str) {
    var matches = str.match(/\S+/g);
    return matches ? matches.length : 0;
}

0

আপনি আপনার কোডটিতে কিছু ভুল পেয়েছেন।

function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar += 1;
        }
    }
    return totalSoFar + 1; // you need to return something.
}
console.log(WordCount("Random String"));

নিয়মিত এক্সপ্রেশন ব্যবহার করার আরও একটি সহজ উপায় রয়েছে:

(text.split(/\b/).length - 1) / 2

সঠিক মানটি প্রায় 1 শব্দের সাথে পৃথক হতে পারে তবে এটি স্থান ছাড়াই শব্দের সীমাও গণনা করে, উদাহরণস্বরূপ "শব্দ-শব্দ.শব্দ"। এবং এটি এমন শব্দ গণনা করে না যাতে অক্ষর বা সংখ্যা থাকে না।


0
function totalWordCount() {
  var str ="My life is happy"
  var totalSoFar = 0;

  for (var i = 0; i < str.length; i++)
    if (str[i] === " ") { 
     totalSoFar = totalSoFar+1;
  }
  totalSoFar = totalSoFar+ 1; 
  return totalSoFar
}

console.log(totalWordCount());

দয়া করে আপনার উত্তর সম্পাদনা করার জন্য কিছু ব্যাখ্যা যুক্ত করুন, কেবলমাত্র উত্তরটি
এড়ান

0
function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 1; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar ++;
        }
    }
    return totalSoFar; 
}
console.log(WordCount("hi my name is raj));

4
কোড-কেবলমাত্র উত্তরগুলি এই সাইটে সাধারণত ভাবা হয়। আপনার কোডটির কিছু মন্তব্য বা ব্যাখ্যা অন্তর্ভুক্ত করতে দয়া করে আপনার উত্তরটি সম্পাদনা করতে পারেন? ব্যাখ্যাগুলির মতো প্রশ্নের উত্তর দেওয়া উচিত: এটি কী করে? কিভাবে এটা কাজ করে? কোথায় যায়? কীভাবে এটি ওপির সমস্যা সমাধান করবে? দেখুন: কিভাবে নতুনকরণ করবেন । ধন্যবাদ!
এডুয়ার্ডো বাইতেলো
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.