即使文件在我的计算机上,程序也找不到文件

时间:2016-06-29 21:13:56

标签: ruby file text

我有" text.txt"保存到我的桌面,我已经尝试移动它的位置并重新保存它以及重命名它。然而它仍然回来告诉它无法找到text.txt。不知道为什么?它是代码还是我保存它的方式?

   #Set line_count to 0, giving a varible for # of lines
    line_count = 0
    #Setting varible text to an empty string, this is where we will collect the text 
    text = ''
    #Open the file, the each method will send EACH part of the object through the block, every time it sends a line line_count will go up 1
    #Then add each line to the variable text, now you have saved all your text in one place
    File.open("text.txt").each do |line|
      line_count += 1
      text << line
    end 
    puts "Lines: #{line_count}"
    #split up text where there are spaces to determine word count
    word_count = text.split.length
    puts "Words: #{word_count}"
    #takes the amount of charaters in the string text - stores it in a variable - then prints it to the console
    char_count = text.length
    puts "Character count: #{char_count}"
    #store the string's lengeth without the spaces using a REGEX then print to the console
    nospace_count = text.gsub(/\s+/,'').length 
    puts "Character count without spaces: #{nospace_count}"
    puts "Number of spaces: #{char_count - nospace_count}"
    #use REGEX to count the number of sentences save to var
    sentence_count = text.split(/\.|\?|!/).length
    puts "Sentences: #{sentence_count}"
    #count paragraphs using regular expression and store them in a var
    para_count = text.split(/\n\n/).length
    puts "Paragraphs: #{para_count}"
    puts "Sentences per paragraph: #{sentence_count / para_count}"
    puts "Words per sentence: #{word_count/sentence_count}"
    stopwords = %w{the a by on for of are with just but and to the my i has in}
    words = text.scan(/\w+/)
    keywords = words.select {|word| !stopwords.include?(word)}
    puts "Keywords: #{keywords.length}"

2 个答案:

答案 0 :(得分:2)

将您的代码和文件放在同一目录中

答案 1 :(得分:0)

尝试提供文件的绝对路径。而不仅仅是文件名。

如果windows然后使用双反斜杠(&#34; \\&#34;)