Python将字符串拆分为下一个句号标点符号

标签 python

每 8 个单词后分割字符串。如果第 8 个单词没有 (. 或 !),移至下一个出现的单词。

我可以从字符串中拆分单词。

with open("file.txt") as c:
    for line in c:
        text = line.split()
        n = 8
        listword = [' '.join(text[i:i+n]) for i in range(0,len(text),n)]
        for lsb in listword:
            print(lsb)

预期输出应该是

I'm going to the mall for breakfast, Please meet me there for lunch. 
The duration of the next. He figured I was only joking!
I brought back the time.

这就是我得到的

I'm going to the mall for breakfast, Please
meet me there for lunch. The duration of 
the next. He figured I was only joking!
I brought back the time.

最佳答案

您正在向单词序列添加换行符。换行的主要条件是最后一个单词以 .! 结尾。另外还有一个关于最小长度的次要条件(8 个字或更多)。以下代码收集缓冲区中的单词,直到满足打印行的条件。

with open("file.txt") as c:
    out = []
    for line in c:
        for word in line.split():
            out.append(word)
            if word.endswith(('.', '!')) and len(out) >= 8:
                print(' '.join(out))
                out.clear()
    # don't forget to flush the buffer
    if out:
        print(' '.join(out))

关于Python将字符串拆分为下一个句号标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56226602/

相关文章:

python - 如何检查字母是否不在单词中?

python - 通过pid获取进程名

python - 如何根据值的相似性将字典拆分为两个单独的字典

python - 如何使用 GDAL python 从 LiDAR 点(X、Y、Z)创建网格?

python - 为什么在函数conway的Python游戏中出现这种语法错误?

python - keras 中用于视频的 tensorflow 后端

python - 两个列表值之间的选定组合

python - 如何在python中创建使用相同值初始化的特定类型的指定维度数组?

python - 混合属性表达式 : aggregate attribute on many side of one to many

Python 套接字接受 block - 防止应用程序退出