我是 python 和 Spacy 新手,我正在通过 spacy 课程学习 Spacy https://course.spacy.io/es/chapter2。在这节课中有这样一个例子:
# Import the Doc and Span classes
from spacy.tokens import Doc, Span
# The words and spaces to create the doc from
words = ["Hello", "world", "!"]
spaces = [True, False, False]
# Create a doc manually
doc = Doc(nlp.vocab, words=words, spaces=spaces)
# Create a span manually
span = Span(doc, 0, 2)
# Create a span with a label
span_with_label = Span(doc, 0, 2, label="GREETING")
# Add span to the doc.ents
doc.ents = [span_with_label]
我知道 doc.ents 是一个 python 元组,因此它必须是不可变的。那么怎么可能像这个例子一样向它添加元素呢?
元组本身作为内存中的对象,是不可变的,但在最后一行中,代码创建了一个全新的元组并将
.ents
变量分配给该新的不可变元组,它不会操作原始元组。
这是一个插图:
创建一个元组并打印其类型以确认它确实是一个元组:
>>> test_tuple = (3, 4, 7, 5)
>>> type(test_tuple)
tuple
尝试改变元组的第一个元素:
>>> test_tuple[0] = "hello"
TypeError: 'tuple' object does not support item assignment
现在尝试将一个新的元组分配给同一个变量:
>>> test_tuple = ("hello", 4, 7, 5)
>>> print(test_tuple)
('hello', 4, 7, 5)
工作得很好!我希望这会有所帮助。