Ordinarily, while working with Python strings, we can have an issue where in we have a gigantic measure of information and we need to perform preprocessing of a specific kind. This can likewise be eliminating stray newline characters in strings. How about we examine certain manners by which this undertaking can be performed. and also while we want to remove the newline from a text file that is added accidentally or to post it anywhere you need to remove newline characters
there are several ways to do so but Two of them are given below-
Method 1: Using the function, Recursion, Loops, FileIO
The first one is much interesting this program shows the number of lines and removes a new line character from a text file. and return the output in another text file with name output.txt at a location that the file exists I recommend you to use this one. This task can be perform using brute force in which we check for “\n” as a string in a string and replace that from each string using the loop.
def breakline(lines): '''program to break every single character present in lines and takes list and returns a list''' nextword="" final=[] for line in lines: lstofline=list(line) for letter in lstofline: nextword=letter final+=lstofline return final def removeline(lst): '''this function removes newline character and takes list''' INDEX=0 for character in lst: if character=='\n': lst[INDEX]=" " INDEX+=1 return lst def lst_2_str(final_list): '''this function convert list in string with single sentance and takes list''' sentance=final_list[0] count=1 for i in final_list: if count<len(final_list): sentance+=final_list[count] count+=1 return sentance print("enter the path of \ file:\n(example:\\folder\\\ file.extention or \ example:/folder/\ file.extention)\n") path_of_file=input() file_2_open=open(rf"{path_of_file}", "r") reading_lines=file_2_open.readlines() str_reading_lines=str(reading_lines) all=removeline(breakline(reading_lines)) input_sentances=lst_2_str(all) output_file=open("output.txt", 'w') output_file.write(input_sentances) output_file.close() print(f"after removing line your sentance\ is >>> {input_sentances} and it is saved \ output.txt") file_2_open.close() |
output will be-
(example:\folder\file.extention or \ example:/folder/file.extention) file.txt there are ***'numbers'*** lines in your file ***your text with out new line charactes***
|
("and your file is also created as output.txt")
Method 2: Using loops
this is a simple program to do it in simple steps but no file is created it returns the value as a string so the code is given below.
def remove_newlines(fname): |
Method 3: Using regex
import re print("enter the path with file & its \ |
0 Comments
Share your views on this blog😍😍