Say I have the function:

dep = TextStructure["He wrote a book. I read the book he wrote.", 
  "DependencyStrings", PerformanceGoal -> "Speed"]

Which outputs:

{"(wrote, 2)((nsubj, (He, 1)), (dobj, (book, 4)((det, (a, 3)))))", \
"(read, 2)((nsubj, (I, 1)), (dobj, (book, 4)((det, (the, 3)), (rcmod, \
(wrote, 6)((nsubj, (he, 5)))))))"}

Firstly, I want to extract each case of nsubj with the list:


I have tried below but to no avail.

 Shortest["subj," ~~ __ ~~ 
    x : (LetterCharacter ~~ __ ~~ WordBoundary) /; x]]

This gets me half way, but it's not good enough:

StringCases[dep, Shortest["subj," ~~ __ ~~ ")"]]

Secondly, I want to get the root of the dependency which is the first word number pair of each sentence.


If it were an expression it would be easy through:

Cases[dep, {s_Symbol, _Integer} :> ToString@s, 1]]

But I need to extract it from a string. Thanks in advance.


Try these:

 "((nsubj, (" ~~ w : WordCharacter .. ~~ ", " ~~ DigitCharacter .. ~~ "))" :> w]

StringCases[dep, "(" ~~ w : WordCharacter .. ~~ ___ :> w]
{{"He"}, {"I", "he"}}

{{"wrote"}, {"read"}}

A Regex attempt:

  RegularExpression["[(]nsubj,\s+[(]([^,]+)"] :> "$1"]&/@dep

{{He}, {I, he}}

  RegularExpression["^[(]([^,]+)"] :> "$1"]&/@dep

{{wrote}, {read}}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.