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.']
因此,只有当句子不以“?”、“!”结尾时,我才需要插入句点 或者 '。'。此外,如果句子以逗号结尾,我需要将其更改为句号。
我的代码在这里:
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)
但它不能正常工作。
解决方案
只需定义一个函数来修复一个句子,然后使用列表推导从旧列表中构造一个新列表:
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()
需要添加新规则时进行改进。
例如,能够根据函数的前两行处理空字符串,以便在尝试从中提取最后一个字符时不会出现异常。
推荐阅读
- bash - How to list the original commits (time and author) per file of a directory with git?
- spring-boot - 使用 @DataJpaTest 进行集成测试
- ansible - 使用 ansible 删除字符串中的反斜杠
- amazon-web-services - Api网关:如何根据调用者的策略授予权限
- android - android.database.CursorIndexOutOfBoundsException:
- javascript - 在巨大的 React.JS webapp 中渲染后加载 JavaScript 脚本
- python-3.6 - 调用 tensorflow2 模型未返回已在 call() 方法中定义的输出
- mysql - 从我的 sql 迁移到 postgres 然后继续更新
- javascript - JavaScript面临的问题
- amazon-web-services - 如何在 AWS DynamoDB 上为失败的 INSERT 尝试设置警报