Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want to use your original code, you have to pass the filename to the <code>finder()</code> function, and open the file there, for each char you are testing for. </p> <p>The reason for this is that the file object (<code>in_file</code>) is a generator, not a list. The way a generator works, is that it returns the next item each time you call their <code>next()</code> method. When you say </p> <pre><code>for line in in_file: </code></pre> <p>The <code>for ... in</code> statement calls <code>in_file.next()</code> as long as the <code>next()</code> method "returns" (it actually use the keyword <code>yield</code>, but don't think about that for now) a value. When the generator doesn't return any values any longer, we say that the generator is exhausted. You can't re-use an exhausted generator. If you want to start over again, you have to make a new generator.</p> <p>I allowed myself to rewrite your code. This should give you the desired result. If anything is unclear, please ask!</p> <pre><code>def finder_character(file_name,character): with open(file_name, "r") as ifile: if character=='vowel': brain_rat='aeiou' elif character=='consonant': brain_rat='bcdfghjklmnpqrstvwxyz' elif character=='space': brain_rat=' ' else: brain_rat='!@#$%^&amp;*()_+=-123456789{}|":?&gt;&lt;,./;[]\'' return sum(1 if c.lower() in brain_rat else 0 for c in ifile.read()) </code></pre> <p><strong>test.txt:</strong></p> <pre><code>eeehhh iii!# kk ="k oo o </code></pre> <p><strong>Output:</strong></p> <pre><code>&gt;&gt;&gt;print(finder_character('test.txt', 'vowel')) 9 &gt;&gt;&gt;print(finder_character('test.txt', 'consonant')) 6 &gt;&gt;&gt;print(finder_character('test.txt', 'space')) 2 &gt;&gt;&gt;print(finder_character('test.txt', '')) 4 </code></pre> <p>If you are having problems understanding the <code>return</code> line, it should be read backwards, like this:</p> <pre><code>Sum this generator: Make a generator with values as v in: for row in ifile.read(): if c.lower() in brain_rat: v = 1 else: v = 0 </code></pre> <p>If you want to know more about generators, I recommend the <a href="https://wiki.python.org/moin/Generators" rel="nofollow">Python Wiki page</a> concerning it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload