python - 如何将值设置为与最后一项中的值相同?

标签 python python-3.x

我有一个文本,我正在将其拆分成一个句子列表,我想找到每个句子的主题。例如,如果文本是“Dogs are great”。 They are so awesome',不得不拆分成'Dogs are great'这两个句子。和“他们太棒了”。然后我使用 for 循环查找每个句子的主语是什么,是“猫”还是“狗”。

sentence_list=['Dogs are great', 'They are so awesome']
for sentence in sentence_list:
    if 'Dog' in sentence:
        subject= 'Dog'
    elif 'Cat' in sentence:
        subject='Cat'

因为“他们”被用作其中一个的替代品,所以我想将该句子的主语设置为与最后一句话相同。所以在这个例子中,两个句子的主语都是“狗”。

最佳答案

您已经有了最后一个值。如果 if 子句和 elif 子句都不为真,则 subject 没有在本次迭代中设置。这意味着它仍将保持与上次迭代相同的值。

sentence_list=['Dogs are great', 'They are so awesome']
for sentence in sentence_list:
    if 'Dog' in sentence:
        subject= 'Dog'
    elif 'Cat' in sentence:
        subject='Cat'
    print(subject)

将导致:

Dog
Dog

关于python - 如何将值设置为与最后一项中的值相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51710105/

相关文章:

python - 如何优化 Flask 的 render_template() 模板

python - 替代已弃用的 sqlite pragma "default_cache_size"

使用 OR 运算符的 Python 正则表达式

python - 将复杂的 ffmpeg 命令转换为 python3

python - 在 pyinstaller 中以窗口模式导出到 EXE 后,Selenium 不起作用

python - f-strings 与 str.format()

python - 使用 pandas 数据框填充 flet 数据表

python - 无法使用 python PIL Image.show 显示图像

python - 如何在Python中生成运行时类

python - 使用 super() 调用父类构造函数与使用父类名称