简体   繁体   中英

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()

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM