1

I want to remove empty lines, dots and commas from my textfile. I am not really sure how to do it. I tried different metods but didnt get any results

filename = "phil.txt"
def countLines():
    """
    Read number of lines in the text file.
    """
    numOflines = 0


    with open(filename) as file:

        for line in file:
            numOflines += 1
    print("Total number of lines is: ", numOflines)
    return numOflines
countLines()

I get 19 lines but the answer should be 17 lines. I addition I want to also remove commas and dots for later use.

zvone
  • 18,045
  • 3
  • 49
  • 77
coder
  • 19
  • 5
  • 1
    How is this code related to _"I want to remove empty lines, dots and commas from my textfile."_? The code is counting lines. What is your question? – zvone Oct 20 '19 at 11:39
  • @zvone I may have expressed myself wrong. What I really want is to remove two empty lines from my textfile. :) – coder Oct 20 '19 at 11:41
  • 1
    Are you saying two of the lines are blank in your file? – DarrylG Oct 20 '19 at 11:42
  • @DarrylG Yes, I figured out how to remove commas and dots, the only part I am have troubles with is the empty lines – coder Oct 20 '19 at 11:43
  • What you really want seems to be: "Count lines in the file, but without the empty lines", right? Did you try putting an `if` before `numOflines += 1`? – zvone Oct 20 '19 at 11:44
  • [Deleting blank lines (or lines with whitespace only)](https://stackoverflow.com/questions/2369440/how-to-delete-all-blank-lines-in-the-file-with-the-help-of-python) – DarrylG Oct 20 '19 at 11:46
  • @DarrylG I figured it out, appreciate it alot. – coder Oct 20 '19 at 11:51

1 Answers1

0

I'd do something like :

replaced_characters = {'\r\n': '\n', '\n\n': '\n', ',': ' ', '.':' ', '  ': ' '}

with open('file.ext', 'r') as f:
    text = f.read()

for k, v in replaced_characters.items():
    text = text.replace(k, v)

print(text)

I haven't tested it.

Loïc
  • 11,804
  • 1
  • 31
  • 49