在Python中添加缺少的句点

在Python中添加缺少的句点,python,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.'] 所以我只需要在一个句子不以“?”,“!”结尾时插入句点或“.”。如果一个句子以逗号结尾,我需要把它改成句号 我的代码在这里: l

我有下一个句子列表:

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)
但是它不能正常工作。

根据,您应该更改为:

b = b + '.' if (not b.endswith('.')) and (not b.endswith('!')) and (not b.endswith('?')) else b
您可以简化为:

b = b + '.' if b and b[-1] not in ('.', '!', '?') else b

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

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.']
通过一个单独的函数,您可以在需要添加新规则时改进
修复句子()


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

“但它不能正常工作”不是一个非常详细的错误报告:-)也许您可以详细说明一下。请注意,当字符串以
结尾时,它不能以
结尾。任何其他可接受结尾的组合也是如此。不能有多个条件返回False,
要求所有条件都返回False。如果数组中有空字符串,会发生什么情况?@simonlink Good point。这是一个需要解决的边缘问题。我编辑了我的答案。你也遗漏了逗号到句点的要求。这是可以理解的,因为OPs代码没有它,但它肯定在文本中。和@Maroun的答案一样。如果其中一个字符串是
'
,会发生什么?我会坚持使用
endswith()
@Simon,看起来我在你提出它之前30秒就解决了这个错误:-)是的,你也可以使用
endswith()
,但是它会使
行中的
if char复杂化,所以我想我会坚持使用我得到的。