Question
The code should be in Python Write a function that given a text string outputs a dict mapping words to corresponding spans. For example, given
The code should be in Python
Write a function that given a text string outputs a dict mapping words to corresponding spans.
For example, given input text='it is what it is', the output should be the following dict:
{
'it': [Span(text='it is what it is', start_pos=0, end_pos=2), Span(text='it is what it is', start_pos=11, end_pos=13)],
'is': [Span(text='it is what it is', start_pos=3, end_pos=5), Span(text='it is what it is', start_pos=14, end_pos=16)],
'what': [Span(text='it is what it is', start_pos=6, end_pos=10)]
}
Use the code from lecture 3 (copied below for your reference) as a part of your code.
import typing
class Span(typing.NamedTuple):
"""
A representation of a substring in a shared text string.
text[start_pos:end_pos] will return the actual substring.
"""
text: str
start_pos: int
end_pos: int
def get_substring(self):
return self.text[self.start_pos:self.end_pos]
s = Span(text, 0, 11)
def get_word_spans(text): spans = [] start_pos = 0 for i, char in enumerate(text): if char == ' ': spans.append(Span(text, start_pos=start_pos, end_pos=i)) start_pos = i + 1 if start_pos < len(text): spans.append(Span(text, start_pos, len(text))) return spans
get_word_spans(text)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started