Jul-19-2020, 01:29 AM
(This post was last modified: Jul-19-2020, 01:29 AM by T_Lafferty.)
I have a text file with words only - no punctuation - that I would like to iterate through and replace every 20th space with a new line/line feed.
Here's what I've tried so far.
I tried this code:
Which doesn't do the trick because it prints the original text under the found text, and in this case looks like a blank line above. Also, this doesn't modify the source file, it just prints to the screen/shell.
Here's an example of what I'd like to do, the words NEWLINE HERE means start a new line. For visual ease, I've numbered each word below to indicate the word's position in the file:
bogus1 bogus2 bogus3 etc. bogus20 NEWLINE HERE
I'm a total noob to python and could really use the help!
Here's what I've tried so far.
I tried this code:
# Build array of lines from file, strip newlines
mylines = [] # Declare an empty list.
with open ('lorem.txt', 'rt') as myfile: # Open lorem.txt for reading text.
for myline in myfile: # For each line in the file,
mylines.append(myline.rstrip('\n')) # strip newline and add to list.
# Locate and print all occurences of space " "
substr = " " # substring to search for.
for line in mylines: # string to be searched
index = 0 # current index: character being compared
prev = 0 # previous index: last character compared
while index < len(line): # While index has not exceeded string length,
index = line.find(substr, index) # set index to first occurrence of "e"
if index == -1: # If nothing was found,
break # exit the while loop.
print(" " * (index - prev) + " ", end='') # print spaces from previous
# match, then the substring.
prev = index + len(substr) # remember this position for next loop.
index += len(substr) # increment the index by the length of substr.
# (Repeat until index > line length)
print('\n' + line); # Print the original string under the spaces'sI borrowed this from https://www.computerhope.com/issues/ch00...he%20data.Which doesn't do the trick because it prints the original text under the found text, and in this case looks like a blank line above. Also, this doesn't modify the source file, it just prints to the screen/shell.
Here's an example of what I'd like to do, the words NEWLINE HERE means start a new line. For visual ease, I've numbered each word below to indicate the word's position in the file:
bogus1 bogus2 bogus3 etc. bogus20 NEWLINE HERE
I'm a total noob to python and could really use the help!
