#dart
#dart
Вопрос:
вот текст, я хочу разделить его слова в списке, но проблема в том, что между двумя абзацами есть запятые, точки и большой интервал, поэтому можно ли предложить РЕГУЛЯРНОЕ ВЫРАЖЕНИЕ для извлечения только целых слов с помощью split(RegExp())
метода?
ввод:
String text = '''
You find so many people are fimble
But you, you are mostly humble
I love the way you wear your hair,
Spreading your style everywhere.
You're like a style fountain.
Enough for a whole mountain.
''';
желаемый результат:
[You, find, so, many, people, are, fimble, But, you, you, are, mostly, humble, I, love, the, way, you, wear, your, hair, Spreading, your, style, everywhere, You're, like, a, style, fountain, Enough, for, a, whole, mountain]
Ответ №1:
Я вижу, что тот же вопрос был задан на Reddit, где я дал свой ответ. Это копия моего решения проблемы.
Кроме того, я бы не использовал split
в этом случае, а просто использовал RegExp
класс для получения совпадений, что намного проще, поскольку легче определить, каким мы определяем слово, вместо того, чтобы пытаться определить, что мы хотим удалить. Итак, что-то вроде этого помогло бы:
void main() {
const text = '''
You find so many people are fimble
But you, you are mostly humble
I love the way you wear your hair,
Spreading your style everywhere.
You're like a style fountain.
Enough for a whole mountain.
''';
final words = [...RegExp(r"[w'] ").allMatches(text).map((e) => e.group(0))];
print(words);
// [You, find, so, many, people, are, fimble, But, you, you, are, mostly,
// humble, I, love, the, way, you, wear, your, hair, Spreading, your, style,
// everywhere, You're, like, a, style, fountain, Enough, for, a, whole,
// mountain]
}
Ответ №2:
Попробуйте var newVar = text.split(‘ ‘)
Найдите его здесь:https://www.tutorialkart.com/dart/dart-split-string /
Комментарии:
1. text.split(‘ ‘) не разделяйте символ » n», в вашем случае у вас есть, если строка содержит n, например, у вас есть какой-то неправильный элемент внутри списка
Ответ №3:
Я почти уверен, что вы можете сделать с регулярным выражением то же самое, мне не нравится использовать регулярное выражение, если я могу использовать логику для создания логического разделения внутри строки.
Я предлагаю черновик кода, чтобы сделать ваше решение настраиваемым, не беспокоясь о логике регулярных выражений. Возможно, вам нужно вернуться к разделенному входу в систему через два года!
void main() {
String value = '''
You find so many people are fimble
But you, you are mostly humble
I love the way you wear your hair,
Spreading your style everywhere.
You're like a style fountain.
Enough for a whole mountain.
''';
//Inside the text can be a , ., in this case I use the solution to introcuce a not usual token inside
//inside the list and after split for this token.
var tokenBySpace = value.split(' ').join("#").split("n").join("#").split("#");
tokenBySpace = tokenBySpace.map((word) => word = cleanString(word.trim())).toList();
tokenBySpace.removeWhere((item) => item.isEmpty); //Easy solution to remove the " . " string
print(tokenBySpace);
}
String cleanString(word){
var grammarRules = [".", ",", "(", ")"];
grammarRules.forEach((rule) => {
if(word.contains(rule)){
word = word.replaceAll(rule, '')
}
});
return word;
}
Результат
[Вы, находите, что так много, людей, являются, ничтожествами, Но, вы, вы, в основном, скромны, , , мне, нравится, то, как, вы, носите, свои, волосы, Распространяя, свой, стиль, повсюду, Вы, как, фонтан, стиля, Достаточный, для, целой, горы]
Решение внутри одной строки может быть
void main() {
String value = '''
You find so many people are fimble
But you, you are mostly humble
I love the way you wear your hair,
Spreading your style everywhere.
You're like a style fountain.
Enough for a whole mountain.
''';
//Inside the text can be a , ., in this case I use the solution to introcuce a not usual token inside
//inside the list and after split for this token.
var tokenBySpace = value.split(' ').join("#")
.split("n").join("#")
.split(".").join("#")
.split(",").join("#")
.split(":").join("#")
.split(";").join("#")
.split("#");
tokenBySpace.removeWhere((item) => item.isEmpty); //Easy solution to remove the " . " string
print(tokenBySpace);
}
Но я предпочитаю первое!
Можете ли вы найти полный пример здесь
код внутри примера приведен ниже
void main() {
var value = '''I preferer the previos solution because is more customizzable,
and help you to preserve some exception inside the text, such as URL
In addition, the this solution, subdivide the logic inside a function.
This solution is made by https://github.com/vincenzopalazzo
''';
//Inside the text can be a , ., in this case I use the solution to introcuce a not usual token inside
//inside the list and after split for this token.
var tokenBySpace = value.split(' ').join("#").split("n").join("#").split("#");
tokenBySpace = tokenBySpace.map((word) => word = cleanString(word.trim())).toList();
tokenBySpace.removeWhere((item) => item.isEmpty); //Easy solution to remove the " . " string
print("------------- FIRST SOLUTION -------------------");
print(tokenBySpace);
value = '''
You find so many people are fimble
But you, you are mostly humble
I love the way you wear your hair,
Spreading your style everywhere.
You're like a style fountain.
Enough for a whole mountain.
''';
tokenBySpace = value.split(' ').join("#")
.split("n").join("#")
.split(".").join("#")
.split(",").join("#")
.split(":").join("#")
.split(";").join("#")
.split("#");
tokenBySpace.removeWhere((item) => item.isEmpty); //Easy solution to remove the " . " string
print("------------- FIRST SOLUTION -------------------");
print(tokenBySpace);
}
String cleanString(word){
var grammarRules = [".", ",", "(", ")"];
grammarRules.forEach((rule) => {
if(word.contains(rule)){
word = word.replaceAll(rule, '')
}
});
return word;
}