如何将文本拆分为字符串?

发布于 2024-12-17 19:50:56 字数 394 浏览 0 评论 0原文

我想将一个文本文件拆分为字符串,您能告诉我如何拆分它吗?例如,给出以下文本文件:

this course in, a style  i 
will have to a modern, language that encourages 
writing clean; and elegant code in a good 

是否有可能将文本文件拆分为如下字符串,例如 2 个单词:

this course
in a
style i
will have
to a
modern language
that encourages
writing clean
and elegant
code in 
a good

您能给我一些提示吗?先感谢您。

I want to split a text file into strings, can you please tell me how to split it. For example, the following text file is given:

this course in, a style  i 
will have to a modern, language that encourages 
writing clean; and elegant code in a good 

Is there any possibility to split the text file into strings like following, for example by 2 words:

this course
in a
style i
will have
to a
modern language
that encourages
writing clean
and elegant
code in 
a good

Can you please give me some hints? Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九八野马 2024-12-24 19:50:56

一些想法:

1) 使用 java.util.Scanner 使用 next(pattern: String) 方法直接从文件中读取标记

,或者

2) 读取所有行 (参见 scala.io.Source ),将它们连接成一个字符串,将字符串分割成一个数组,然后使用 grouped 方法进行分割将其放入 2 个元素的子数组中

Some ideas:

1) Use java.util.Scanner to read in tokens direct from the file using the next(pattern: String) method

or

2) Read in all lines (see scala.io.Source), concatenate them into a single string, split the string into an array, then use the grouped method to split that into sub-arrays of 2 elements

无法回应 2024-12-24 19:50:56

除了路易吉的回答。

3)你应该考虑过滤掉标点符号。

4)另一个提示:

scala> val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val listOfTwoElements = list.sliding(2).toList
listOfTwoElements: List[List[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(4, 5), List(5, 6), List(6, 7), List(7, 8), List(8, 9), List(9, 10))

In addition to Luigi´s answer.

3) You should think about filtering out the punctuation.

4) Another hint:

scala> val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val listOfTwoElements = list.sliding(2).toList
listOfTwoElements: List[List[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(4, 5), List(5, 6), List(6, 7), List(7, 8), List(8, 9), List(9, 10))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文