|
| 1 | +class Textfile: |
| 2 | + |
| 3 | + def __init__(self, filename): |
| 4 | + |
| 5 | + file = open(filename) |
| 6 | + content = file.read() |
| 7 | + file.close |
| 8 | + self.file = content |
| 9 | + |
| 10 | + def nchars(self): |
| 11 | + |
| 12 | + charnum = 0 |
| 13 | + content = self.file |
| 14 | + charnum = len(content) |
| 15 | + return charnum |
| 16 | + |
| 17 | + def nwords(self): |
| 18 | + |
| 19 | + numwords = 0 |
| 20 | + content= self.file |
| 21 | + content = content.split() |
| 22 | + numwords = len(content) |
| 23 | + return numwords |
| 24 | + |
| 25 | + def nlines(self): |
| 26 | + |
| 27 | + numlines = 0 |
| 28 | + content = self.file |
| 29 | + content = content.split('\n') |
| 30 | + numlines = len(content) |
| 31 | + return numlines |
| 32 | + |
| 33 | + def read(self): |
| 34 | + |
| 35 | + return self.file |
| 36 | + |
| 37 | + def readlines(self, n): |
| 38 | + |
| 39 | + content = self.file |
| 40 | + content = content.split('\n') |
| 41 | + return content |
| 42 | + |
| 43 | + def grep(self, string): |
| 44 | + |
| 45 | + result = '' |
| 46 | + lines = [] |
| 47 | + content = self.file |
| 48 | + content = content.split('\n') |
| 49 | + for i in range(len(content)): |
| 50 | + if string in content[i]: |
| 51 | + lines.append(i) |
| 52 | + for line in lines: |
| 53 | + result += '{}: '.format(line) |
| 54 | + result +='{} \n'.format(content[line]) |
| 55 | + print(result) |
| 56 | + |
| 57 | + def words(self): |
| 58 | + |
| 59 | + content = self.file |
| 60 | + content = content.split() |
| 61 | + content = list(set(content)) |
| 62 | + return content |
| 63 | + |
| 64 | + def occurrences(self): |
| 65 | + |
| 66 | + ocur = {} |
| 67 | + content = self.file |
| 68 | + content = content.split() |
| 69 | + content = set(content) |
| 70 | + for word in content: |
| 71 | + ocur[word] = 0 |
| 72 | + content = self.file.split() |
| 73 | + for word in content: |
| 74 | + ocur[word] += 1 |
| 75 | + return ocur |
| 76 | + |
| 77 | + def average(self): |
| 78 | + content = self.file |
| 79 | + for symbol in '.?!': |
| 80 | + content = content.replace(symbol, '%') |
| 81 | + content = content.replace('\n', '') |
| 82 | + content = content.split('%') |
| 83 | + avg = 0 |
| 84 | + wordssentence = [] |
| 85 | + morewords = 0 |
| 86 | + fewerwords = 100 |
| 87 | + for i in range(len(content)-1): |
| 88 | + wordssentence.append(content[i].split()) |
| 89 | + for listwords in wordssentence: |
| 90 | + for word in listwords: |
| 91 | + avg += 1 |
| 92 | + avg = avg / len(content) |
| 93 | + for i in range(len(wordssentence)): |
| 94 | + if len(wordssentence[i]) > morewords: |
| 95 | + morewords = len(wordssentence[i]) |
| 96 | + for i in range(len(wordssentence)-1): |
| 97 | + if len(wordssentence[i])<fewerwords: |
| 98 | + fewerwords = len(wordssentence[i]) |
| 99 | + tupla = (avg, morewords, fewerwords) |
| 100 | + return tupla |
| 101 | + |
| 102 | + |
0 commit comments