Find the most used word in the text in flutter - flutter

I'm calculating how many different words there are. How can I find the most used word in the text. How can I add this to the code.
int kacFarkliKelime(String metin) {
String yeniMetin = metin.replaceAll(RegExp(r'[^\w\s]+'), "");
List<String> liste = yeniMetin.split(
" ",
);
List farklilar = [];
liste.forEach((element) {
String sorgulanan = element.toLowerCase();
if (!farklilar.contains(sorgulanan)) {
farklilar.add(sorgulanan);
}
});
if(farklilar[0])
return farklilar.length;
}

I'd build a Map<String, int> that'd count each word as it is seen, then get a list of keys sorted by descending value order. (There's a few handy "sort by" functions in package:collection to help with that.) The code for that would look like:
var words = (use a regex to extract words);
var count = <String,int>{};
for (final w in words) {
count[w] = 1 + (count[w] ?? 0);
}
var ordered = count.keys.toList();
ordered.sort((a, b) => count[b].compareTo(count[a]));
Now the first element of ordered is the word with the most appearances in the text.

Related

how can I check if any word of a string matches a word in a given list?

for example if I have a string = "I Like To Play Football" and a list = [Car,Ball,Door,Sky] it should give true.
Use any of list
var list = ["Car","Ball","Door","Sky"];
String text = "i like to play football";
if (list.any((item) => text.toLowerCase().contains(item))) {
//Text has a value from list
}
Here You Go:
void main() {
final String tempString = "I Like To Play Football";
final List<String> tempList = ["Car","Ball","Door","Sky"];
for(var i=0; i < tempList.length; i ++) {
if(tempString.contains(tempList.elementAt(i).toLowerCase())){
print("Found and its ${tempList[i]}");
}
}
}
Regex is your friend here. You can make a simple regex that uses each string in the array as an option (and make it case insensitive) then run the match. I've made an example here in javascript, but it's easy to do in dart
https://api.dart.dev/stable/2.16.1/dart-core/RegExp-class.html
const source = "I Like To Play Football";
const toMatch = ["Car","Ball","Door","Sky"];
let regexString = '';
for (const option of toMatch) {
//adding | modifier after string. Last one is redundant of course
//also I'm not checking for special regex characters in toMatch, but that might be necessary.
regexString += option + '|';
}
// using slice to remove last |
console.log(regexString.slice(0, -1));
const regexp = new RegExp(regexString.slice(0, -1), 'i');
console.log(source.match(regexp));
Here's a short version:
var src = 'I Like To Play Football'.split(' ');
var list = ['Car','Ball','Door','Sky'];
var result = list.any((x) => src.any((y) => y.toLowerCase().contains(x.toLowerCase())));
print(result);

Dart/Flutter: How can i calculate values of multiple maps which contains same key?

I am new to Dart and i got stuck at this point for days.
I have multiple maps and these maps follow the same pattern (date:value) but their lengths are different. And these maps are increased dynamically.
For example:
Map1:{01.01.2021:2,02.01.2021:5,03.01.2021:3},
Map2:{02.01.2021:10,03.01.2021:4,04.01.2021:8},
Map3...
Map4...
...
I want to combine these maps and sum the values that contains the same key and store it in an another map. For the different keys, there will be no calculation and store as it is.
Result for Map1 & Map2:
Combined Map{01.01.2021:2,02.01.2021:(5+3),03.01.2021:(3+4),04.01.2021:8}
How can i perform such an operation considering that these maps are iterable inside a class or inside an another list.
Thank you in advance.
Here you go! Paste this on DartPad
This will work with any number of maps inside data map
Any questions fell free to ask me in the comments.
void main() {
final data = {
'Map1': {'01.01.2021':2,'02.01.2021':5,'03.01.2021':3},
'Map2': {'02.01.2021':10,'03.01.2021':4,'04.01.2021':8},
};
final finalData = {};
for(final key in data.keys) {
for(final date in data[key]!.keys) {
final initialValue = finalData[date];
if(initialValue == null) {
finalData[date] = data[key]![date];
} else {
finalData[date] = initialValue + data[key]![date];
}
}
}
// {01.01.2021: 2, 02.01.2021: 15, 03.01.2021: 7, 04.01.2021: 8}
print(finalData);
}
The inner loop can be written more succinctly using the tertiary operator
for (final date in data[key]!.keys) {
final initialValue = finalData[date];
finalData[date] = initialValue == null
? data[key]![date]
: initialValue + data[key]![date];
}
or the null aware operator (??)
for (final date in data[key]!.keys) {
finalData[date] = data[key]![date]! + (finalData[date] ?? 0);
}

apending Text in fluttre Dart

I have number of Strings coming from an API.
What I want is to merge all Strings together...
What I've done so far is store all Strings in an Array and convert that to a String:
var a = List<String>();
a.add("\n \u2022 " + "test1");
a.add("\n \u2022 " + "test2");
Result:
[•test1
•test2
]
Expected:
bulleted lists without [] .
Is there a better way to do this?
This code sample should answer your questions:
void main() {
const itemPrefix = " \u2022 ";
// create a growable list of strings
final strings = <String>[];
// add some items to it
strings.add("test1");
strings.add("test2");
// create a single string joining the items
String result = strings
// prepend the bullet point to each item
.map((item) => "${itemPrefix}$item")
// put a new-line between each item, joining the items to a String
.join('\n');
print(result);
}

Extract number and separate with comma from list in Flutter

List listFinal = [];
So listFinal have values from multiple list inside like below.
[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]]
How do I make this list so that it only extract numbers and separate with comma?
End result should be like
[1113335555, 2223334555, 5553332222]
I can think of trimming or regexp but not sure how to pull this off.
many thanks.
Try this
void main() {
List<String> numberList=[];
List<List<dynamic>> demoList=[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]];
for(int i=0;i<demoList.length;i++){
numberList.addAll(demoList[i].map((e) => e.toString().split(":")[1].replaceAll("-", "")).toList());
}
print(numberList.toString());
}
Here is an example to get you started. This doesn't handle things like malformed input strings. First step is to "flatten" the list with .expand, and then for each element of the flattened iterable use a regex to extract the substring. Other options might include using .substring to extract exactly the last 12 characters of the String.
You can see this in action on dartpad.
void main() {
final input = [
['test: 111-333-5555', 'test2: 222-333-4555'],
['test3: 555-333-2222']
];
final flattened = input.expand((e) => e); // un-nest the lists
// call extractNumber on each element of the flattened iterable,
// then collect to a list
final result = flattened.map(extractNumber).toList();
print(result);
}
final _numberRegExp = RegExp(r'.*: ([\d-]+)$');
int extractNumber(String description) {
var numberString = _numberRegExp.firstMatch(description).group(1);
return int.parse(numberString.replaceAll('-', ''));
}
Let's do this in a simple way.
List<List<String>> inputList = [
["test: 111-333-5555", "test2: 222-333-4555"],
["test3: 555-333-2222"]
];
List resultList = [];
print('Input List : $inputList');
inputList.forEach((subList){
subList.forEach((element){
var temp = element.split(' ')[1].replaceAll('-', '');
resultList.add(temp);
});
});
print('Output List : $resultList');
Here I have taken your list as inputList and stored the result in resultList.
For each element of inputList we get a sub-list. I have converted the elements of that sub-list into the needed format and added those into a List.
Happy Coding :)

RavenDb Suggestions - return multiple-contexts words

I'm trying to get context based suggestions result from RavenDb, the purpose is ui dropdown with auto suggestion from large amount of data on server, each keystroke (in 400ms) is sent to retrieve suggestions.
The suggestion i need is with multiple words by context.
let's say i'm looking for 'Harry Potter', i have documents with just 'Harry' and some docs with only 'Potter', and documents with both.
But if i type 'harre poter' i would get one word suggestions.
i tried searching with multiple words (demonstrated here - suggest.Term = "(word1 word2)";), but the result is list of one words. i want to type 'harre poter' and get suggestion of 'Harry Potter'
i even tried querying multiple times with each word, but the result are not context based, in other word - there is no connection between them.
var words = text.Split(new String[] {" "}, StringSplitOptions.RemoveEmptyEntries).ToList();
var sugegstions = new List<SuggestionQuery>();
foreach (var word in words)
{
var suggest = new SuggestionQuery();
suggest.Field = "Body";
suggest.Term = word;
suggest.Popularity = true;
suggest.MaxSuggestions = 5;
suggest.Distance = StringDistanceTypes.Levenshtein;
sugegstions.Add(suggest);
}
var results = new List<SuggestionQueryResult>();
foreach (var suggest in sugegstions)
{
SuggestionQueryResult result =
s.Query<Book, Books_ByBody>().Suggest(suggest);
results.Add(result);
}
i looked in this SO question, and tried it too, but the results are the docs not suggestions.
my index is : `
public class Books_ByBody : AbstractIndexCreationTask
{
public Books_ByBody()
{
Map = books from book in books
select new
{
book.Body,
};
Indexes.Add(x => x.Body, FieldIndexing.Analyzed);
Suggestion(x => x.Body);
}
}
`