我需要将文本分成段落并能够处理每个段落。我怎样才能做到这一点?每 2 个段落之间至少可以有 1 个空行。像这样:
Hello world,
this is an example.
Let´s program something.
Creating new program.
这个灵魂作品:
text.split('\n\n')
尝试
result = list(filter(lambda x : x != '', text.split('\n\n')))
这不是一个完全微不足道的问题,标准库似乎没有任何现成的解决方案。
示例中的段落被至少两个换行符分割,不幸的是,这使得
text.split("\n\n")
无效。我认为,相反,通过正则表达式分割是一种可行的策略:
import fileinput
import re
NEWLINES_RE = re.compile(r"\n{2,}") # two or more "\n" characters
def split_paragraphs(input_text=""):
no_newlines = input_text.strip("\n") # remove leading and trailing "\n"
split_text = NEWLINES_RE.split(no_newlines) # regex splitting
paragraphs = [p + "\n" for p in split_text if p.strip()]
# p + "\n" ensures that all lines in the paragraph end with a newline
# p.strip() == True if paragraph has other characters than whitespace
return paragraphs
# sample code, to split all script input files into paragraphs
text = "".join(fileinput.input())
for paragraph in split_paragraphs(text):
print(f"<<{paragraph}>>\n")
编辑添加:
使用状态机方法可能更干净。这是一个使用生成器函数的相当简单的示例,它的额外好处是一次一行地流式传输输入,而不是将输入的完整副本存储在内存中:
import fileinput
def split_paragraph2(input_lines):
paragraph = [] # store current paragraph as a list
for line in input_lines:
if line.strip(): # True if line is non-empty (apart from whitespace)
paragraph.append(line)
elif paragraph: # If we see an empty line, return paragraph (if any)
yield "".join(paragraph)
paragraph = []
if paragraph: # After end of input, return final paragraph (if any)
yield "".join(paragraph)
# sample code, to split all script input files into paragraphs
for paragraph in split_paragraph2(fileinput.input()):
print(f"<<{paragraph}>>\n")
我通常会拆分然后过滤掉“”并剥离。 ;)
a =\
'''
Hello world,
this is an example.
Let´s program something.
Creating new program.
'''
data = [content.strip() for content in a.splitlines() if content]
print(data)
这对我有用:
text = "".join(text.splitlines())
text.split('something that is almost always used to separate sentences (i.e. a period, question mark, etc.)')
更容易。我也有同样的问题。
只需更换双 输入一个您在文本中很少看到的术语(此处为 3/4):
a ='''
Hello world,
this is an example.
Let´s program something.
Creating new program.'''
a = a.replace("\n\n" , "¾")
splitted_text = a.split('¾')
print(splitted_text)