【问题标题】:Dynamically create hashes within arrays within arrays [closed]在数组内的数组内动态创建哈希[关闭]
【发布时间】:2013-12-18 14:09:26
【问题描述】:

我正在创建一个数组: 所有单词的哈希 在所有段落数组中 一个文件夹中所有文件的数组

我相信我已经在所有段落的数组中获得了所有单词的哈希值。但是,为每个文件都这样做,并为每个文件创建一个特定的密钥,这太过分了。

到目前为止,这是我的代码。为文件夹中的所有文件创建唯一数组并将该文件的所有段落数组放入 files 数组时出错。

numberfiles = Dir.glob(File.join('**', '*')).select { |file| File.file?(file) }.count
    countfiles+1
    # HERE I MAKE THE ARRAY FOR ALL FILES
        filesArray = Array.new(numberfiles.to_i, Hash.new)
        for j in 0...numberfiles.to_i do
            filesArray[j] = Hash.new    
        end

#now to open all textfiles..
Dir.glob("*.txt").each do |textfile|


    lines = File.readlines(textfile)
    text = lines.join
    paragraph_count = text.split("\.\r").length
    #create array with key for every paragraph
    testArray = Array.new(paragraph_count.to_i, Hash.new)
    for $i in 0...paragraph_count.to_i do
        testArray[$i] = Hash.new    
    end
    words_in_each_paragraph = Array.new

    i = 0

在这里,我想将所有测试数组保存到文件数组中。那是行不通的:

File.foreach(textfile, "\.\r") do |paragraph|
    word_hash = {}
    paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
        h[w] = []
    }
    words_in_each_paragraph << word_hash
    testArray[i][:value] = word_hash
    filesArray[j][:file] = testArray # HERE IT GOES WRONG
    i += 1
end

puts filesArray[1]
end

【问题讨论】:

  • 你为什么要粘贴所有代码..只给出痛苦的区域..
  • 你为什么使用for循环?使用each
  • Arup,我正在粘贴大部分代码,以便清楚上下文:它是 [currently-not-working-and-not-dynamic ] 数组

标签: ruby arrays loops hash


【解决方案1】:

我不完全确定您要做什么,但我知道您实际上不必在 Ruby 中预先分配数组的大小。以下代码遍历每个 .txt 文件,将它们分成段落并将这些段落的每个单词放在哈希中。该单词哈希被附加到段落数组中,而段落数组又被附加到文件数组中。

files = []

Dir.glob("*.txt").each do |textfile|
  paragraphs = []
  File.foreach(textfile, "\n\n") do |paragraph|
    words = Hash.new(0)
    paragraph.split(/\W+/).each {|word| words[word] += 1}
    paragraphs << words
  end
  files << paragraphs
end

p files

【讨论】:

    【解决方案2】:

    如果您想对可枚举事物的每个元素执行某项操作并将结果存储在数组中,请考虑map

    result = Dir.glob("*.txt").map do |textfile|
      File.read(textfile).split("\n\n").map do |paragraph| #again!
        words = Hash.new(0)
        paragraph.split(/\W+/).each {|word| words[word] += 1} #copied from @Jonas Elfström
      end
    end
    p result
    

    【讨论】:

    • 这就是要走的路。现在我想改变我的答案。 :)
    • @JonasElfströmsteenslag 和 steenslag:很棒的工作。这就是我所需要的(我不得不承认:从 50 行到 7 行是纯粹的美)。现在,在此之后如何映射/索引所有内容?对第二个文件的第二段的引用是什么? / 我如何在一个循环中引用所有文件的所有段落?
    • files[1][1] 包含第二个文件的第二段。如果您想遍历所有段落,只需首先使用 files.flatten。还要考虑使用map 是否更合适。
    猜你喜欢
    • 2018-01-23
    • 2012-06-29
    • 2023-03-31
    • 2016-02-25
    • 2014-04-13
    • 2021-02-05
    • 2011-04-21
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多