如何将一串句子重新格式化为每行一个句子

2024-09-28 05:28:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个只有一个大字符串的文件。在这个字符串中,有些句子以3个数字结尾,如下所示:

sees mouse . 1980 1 1 sheep erythrocytes mouse 1980 6 5 seen mouse 1980 8 8

我想将其更改为文件/输出如下所示:

sees mouse . 1980 1 1

sheep erythrocytes mouse 1980 6 5

seen mouse 1980 8 8

下面是我用来解决这个问题的代码:

with open('ngram_test') as f:
for line in f:
    #print(line)
    for word in line.split():
        print(word)

但是,它只打印字符串中的每个单词和换行符。任何帮助将不胜感激!在


Tags: 文件字符串infor结尾line数字句子
3条回答

使用Regex,可以在每个模式出现后添加新行(\n):

import re
s = "sees mouse . 1980 1 1 sheep erythrocytes mouse 1980 6 5 seen mouse 1980 8 8"
pattern = r"(\d{4}\s\d{1,2}\s\d{1,2})"
for match in re.findall(pattern, s):
    s = re.sub(match, f'{match}\n', s)

输出:

^{pr2}$

您需要使用regexp并查找所需字符串的索引,然后将其删除。在

import re

pattern = re.compile(r'[a-zA-Z\.\s]+\d{4}\s+?\d{1,2}\s+?\d{1,2}')
print([(m.start(0), m.end(0)) for m in re.finditer(pattern, s)])

假设输入受到问题中提供的字符串的限制,这将起作用。如果不是,则需要扩展模式。在

一个简单的正则表达式就可以了

a='sees mouse . 1980 1 1 sheep erythrocytes mouse 1980 6 5 seen mouse 1980 8 8'
count=0
for i in re.finditer('(\d \d \d)',a):
    print(a[count:i.end()].strip())
    count=i.end()

相关问题 更多 >

    热门问题