use*_*619 1 python regex string
我想用 Python 编写一个正则表达式来执行以下操作
转换所有以“.”结尾的句子[alphanumeric]\n并将其替换为“。”
例如
I went there
I also went there.
It is
That-
I too went there!
It went there?
It is 3
Run Code Online (Sandbox Code Playgroud)
所以假设我们有
应转换为
I went there.
I also went there.
It is.
That-
I too went there!
It went there?
It is 3.
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
编辑:输入字符串是
s = "I went there\nI also went there.\nIt is\n\nThat-\nI too went there!\nIt went there?\nIt is 3"
Run Code Online (Sandbox Code Playgroud)
还, ”?” 不应附加“.”
EDIT2:我修改了示例,使其包含一个 double\n和一个以 结尾的句子-。因此“-”不应附加“.”。
尝试这样的事情:
s = 'I went there'
if s[-1] not in ['!', ',', '.', '\n']:
s += '.'
Run Code Online (Sandbox Code Playgroud)
编辑:
根据您的新输入,以下操作应该有效:
new_string = ''.join('{}.\n'.format(item) if (item and item[-1] not in '!?.,-') else '{}\n'.format(item) for item in s.split('\n'))
Run Code Online (Sandbox Code Playgroud)
如果您不想要\n末尾的new_string,可以将其删除:
new_string = new_string.rstrip('\n')
Run Code Online (Sandbox Code Playgroud)
输出:
>>> s = "I went there\nI also went there.\nIt is\n\nThat-\nI too went there!\nIt went there?\nIt is 3"
>>> new_string = ''.join('{}.\n'.format(item) if (item and item[-1] not in '!?.,-') else '{}\n'.format(item) for item in s.split('\n'))
>>>
>>> print(new_string)
I went there.
I also went there.
It is.
That-
I too went there!
It went there?
It is 3.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
942 次 |
| 最近记录: |