字符串和数组中的文件工作,我有一个文本文件(“dict.txt”)的8K +英文单词:与红宝石
apple -- description text
angry -- description text
bear -- description text
...
我需要后删除所有文字“ - ”上的每一行我的文件。
什么是解决这个问题的最简单最快速的方法?
字符串和数组中的文件工作,我有一个文本文件(“dict.txt”)的8K +英文单词:与红宝石
apple -- description text
angry -- description text
bear -- description text
...
我需要后删除所有文字“ - ”上的每一行我的文件。
什么是解决这个问题的最简单最快速的方法?
与开始:
words = [
'apple -- description text',
'angry -- description text',
'bear -- description text',
]
如果你想只说了句前述--
:
words.map{ |w| w.split(/\s-+\s/).first } # => ["apple", "angry", "bear"]
或者:
words.map{ |w| w[/^(.+) --/, 1] } # => ["apple", "angry", "bear"]
如果你想要的话和--
:
words.map{ |w| w[/^(.+ --)/, 1] } # => ["apple --", "angry --", "bear --"]
如果目标是没有说明,以创建一个版本的文件:
File.open('new_dict.txt', 'w') do |fo|
File.foreach('dict.txt') do |li|
fo.puts li.split(/\s-+\s/).first
end
end
一般情况下,为了避免可扩展性问题,如果/当你输入文件增长到巨大的比例,使用foreach
遍历输入文件并将其作为单行处理。只要逐行迭代或尝试将其全部浸入并作为缓冲区或数组进行处理,就可以达到处理速度。啜huge一个巨大的文件可能会减慢机器的抓取速度或使您的代码崩溃,使其无限缓慢;逐行IO意外快速,没有潜在的问题。
Sn,我在查找文档时遇到了一些困难,我注意到(对于给定的数组“文字”),您可能已经使用过'w [0]
它是字符串的一部分:['String。[]'](http://www.ruby-doc.org/芯2.0.0/String.html#方法-I-5B-5D)。 –
File.read("dict.txt").gsub(/(?<=--).*/, "")
输出
apple --
angry --
bear --
...
lines_without_description = File.read('dict.txt').lines.map{|line| line[0..line.index('-')+1]}
File.open('dict2.txt', 'w'){|f| f.write(lines_without_description.join("\n"))}
如果你想要的速度,你可能要考虑一下在命令行上sed
做:
sed -r 's/(.*?) -- .*/\1/g' <dict.txt> new_dict.txt
这将创建一个新的文件仅包含单词的new_dict.txt
。
您的目标是编辑文件或只是将文字读入数组中? – hirolau
如果您将文件读入数组'a'('a [0] ='apple - description text'',只需'a.map!{| e | e [/.+--/]'。 –