繁体   English   中英

Python:如果第一个单词全部大写,则在句子中第一个单词后添加新行

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

我正在尝试修改txt文件。 该文件是电影脚本,格式为:

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

我想在字符后插入新行:

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

如何在python中执行此操作? 我目前有:

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

如其中一项注释中所建议,可以使用splitisupper来完成此操作。 下面提供了一个示例:

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

您的代码有多个问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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