3

I am reading a blog post related to a Recurrent Neural Network for Natural Language Processing and am trying to recreate the code to practice with. The sample code uses a method to read in a .txt file called file().read(). I am not familiar with this method and would like to know if it's contained in an importable module, or at least what it would return so I could recreate the method with with different code.

I did attempt to substitute a with open(filename) as f but it did not return the data in the same format as the file().read() method seems to. "File" isn't the easiest term to Google if you're looking for a specific result!

def train_char_lm(fname, order=4):
    data = file(fname).read()
    lm = defaultdict(Counter)
    pad = "~" * order
    data = pad + data
    for i in xrange(len(data)-order):
        history, char = data[i:i+order], data[i+order]
        lm[history][char]+=1
    def normalize(counter):
        s = float(sum(counter.values()))
        return [(c,cnt/s) for c,cnt in counter.iteritems()]
    outlm = {hist:normalize(chars) for hist, chars in lm.iteritems()}
    return outlm
Epiphannie
  • 31
  • 1
  • 3
    `open(filename).read()` should work. – Blorgbeard May 30 '19 at 19:58
  • https://stackoverflow.com/questions/47838405/porting-a-sub-class-of-python2-file-class-to-python3 – Supratim Haldar May 30 '19 at 20:00
  • 1
    I'd use `data = f.read()` with a `with open(filename) as f:` block as you suggested rather than the bare `open().read()`, might as well use the auto-close from the context manager. But otherwise, yeah, that's the Python 3+ replacement. – Peter DeGlopper May 30 '19 at 20:03

1 Answers1

1

Typing

help(file)

into the IDLE interpreter yields

Help on class file in module __builtin__:

plus additional useful info for you. It is part of the built-in module.

17th Lvl Botanist
  • 155
  • 1
  • 3
  • 12