簡體   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