我有一个文本,我正在将其拆分成一个句子列表,我想找到每个句子的主题。例如,如果文本是“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/