Feynman27
Feynman27

Reputation: 3267

Python: Add a new line after the first word in a sentence if the first word is all caps

I'm trying to modify a txt file. The file is a movie script in the format:

BEN We’ve discussed this before.
LUKE I can be a Jedi. I’m ready. 

I'd like insert a new line after the character:

BEN 
We’ve discussed this before.
LUKE 
I can be a Jedi. I’m ready.

How do I do this in python? I currently have:

def modify_file(file_name):
  fh=fileinput.input(file_name,inplace=True)
  for line in fh:
    split_line = line.split()
    if(len(split_line)>0):
      first_word = split_line[0]
      replacement = first_word+'\n'
      first_word=first_word.replace(first_word,replacement)
      sys.stdout.write(first_word)
      fh.close()

Upvotes: 0

Views: 943

Answers (2)

vks
vks

Reputation: 67978

There are multiple problems with your code.

import fileinput
def modify_file(file_name):
    fh=fileinput.input("output.txt",inplace=True)
    for line in fh:
        split_line = line.split()
            if(len(split_line)>0):
                x=split_line[0]+"\n"+" ".join(split_line[1:])+"\n"
                sys.stdout.write(x)

    fh.close()  #==>this cannot be in the if loop.It has to be at the outer for level

Upvotes: 0

Jared Goguen
Jared Goguen

Reputation: 9010

As suggested in one of the comments, this can be done using split and isupper. An example is provided below:

source_path = 'source_path.txt'

f = open(source_path)
lines = f.readlines()
f.close()

temp = ''
for line in lines:
    words = line.split(' ')
    if words[0].isupper():
        temp += words[0] + '\n' + ' '.join(words[1:])
    else:
        temp += line

f = open(source_path, 'w')
f.write(temp)
f.close()

Upvotes: 2

Related Questions