首页 > 解决方案 > 在 Python 中添加缺失的句点

问题描述

我有下一个句子列表:

list_of_sentense = ['Hi how are you?', 'I am good', 'Great!', 'I am doing good,', 'Good.']

我想将其转换为:

['Hi how are you?', 'I am good.', 'Great!', 'I am doing good.', 'Good.']

因此,只有当句子不以“?”、“!”结尾时,我才需要插入句点 或者 '。'。此外,如果句子以逗号结尾,我需要将其更改为句号。

我的代码在这里:

list_of_sentense_fixed = []
for i in range(len(list_of_sentense)):
    b = list_of_sentense[i]
    b = b + '.' if (not b.endswith('.')) or (not b.endswith('!')) or (not b.endswith('?')) else b
    list_of_sentense_fixed.append(b)

但它不能正常工作。

标签: python

解决方案


只需定义一个函数来修复一个句子,然后使用列表推导从旧列表中构造一个新列表:

def fix_sentence(str):
    if str == "":                    # Don't change empty strings.
        return str
    if str[-1] in ["?", ".", "!"]:   # Don't change if already okay.
        return str
    if str[-1] == ",":               # Change trailing ',' to '.'.
        return str[:-1] + "."
    return str + "."                 # Otherwise, add '.'.

orig_sentences = ['Hi how are you?', 'I am good', 'Great!', 'I am doing good,', 'Good.']
fixed_sentences = [fix_sentence(item) for item in orig_sentences]
print(fixed_sentences)

这将按要求输出:

['Hi how are you?', 'I am good.', 'Great!', 'I am doing good.', 'Good.']

使用单独的功能,您可以在fix_sentence()需要添加新规则时进行改进。

例如,能够根据函数的前两行处理空字符串,以便在尝试从中提取最后一个字符时不会出现异常。


推荐阅读